javascript 定时任务封装

/** 
 * 定时任务 
 * 间隔时间,执行次数,要带的参数,要执行的函数. 
 */  
var TimingTask = function(time,count,param,fun){  
    this.id = -1;           //编号  
    this.exectionCount = 0; //执行了多少次  
    if(typeof time === 'function'){  
        this.fun = time;  
        this.time = 3000;  
        this.count = -1;  
    }else  
    if(typeof param === 'function'){  
        this.time = time;  
        this.count = count;  
        this.fun = param;  
    }else  
    if(typeof count === 'function'){  
        this.time = time*1000;  
        this.fun = count;  
        this.count = -1;  
    }else{  
        this.time = time*1000;  
        this.count = count;  
        this.param = param;  
        this.fun = fun;  
    }  
}  
TimingTask.prototype = {  
    add : function(time,count,fun){ //间隔秒数,执行次数,执行方法  
        if(typeof time === 'function'){  
            this.fun = time;  
        }else  
        if(typeof count === 'function'){  
            this.time = time;  
            this.fun = count;             
        }else{  
            this.time = time;  
            this.count = count;  
            this.fun = fun;  
        }  
    },  
    start : function(){  
        if(this.id === -1){ //说明还没开始  
            this.exectionCount = 0;  
            this.id = setInterval((function(param) {  
                return function() {  
                    if(param.count > 0){  
                        if(param.exectionCount >= param.count){  
                            param.stop();  
                            return;  
                        }  
                    }  
                    param.exectionCount ++;  
                    param.fun(param);  
                }  
            })(this), this.time);  
        }  
    },  
    stop : function(){  
        clearInterval(this.id);  
        this.id = -1;  
    }  
};  
  
//使用方法  
var chart = {test:'testString'};  
var change3D = new TimingTask(0.4,1,chart,function(chartObj){   //0.4秒后改回3D效果,执行1次就够了.  
                     var chart = chartObj.param;  
                     alert(chart.test);              });  
                 change3D.start();  //执行  

参考文献:

[1].  JS定时任务封装 - - ITeye博客

 

转载于:https://www.cnblogs.com/yqmcu/p/10537745.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值