JS定时任务封装

本文详细介绍了如何使用JavaScript创建并管理定时任务,包括设置间隔时间、执行次数、携带参数及执行函数。通过实例展示了如何将定时任务应用于改变页面元素状态,如在特定时间后改变3D效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/**
* 定时任务
* 间隔时间,执行次数,要带的参数,要执行的函数.
*/
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(); //执行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值