/**
* 定时模拟器
*
* @author yuyang
*
* @version 2017-03-01
*
* @returns
*/
function TimerSimulator(task, times, name) {
/** 类名 */
this.imClassName = "TimerSimulator";
/**
* 计数器
*/
this.counter = 0;
/**
* taskId
*/
this.taskId = null;
/**
* 时间
*/
this.times = times;
/**
* 任务
*/
this.task = task;
/**定时器名称*/
this.name = name;
/**
* 启动定时任务(模拟)
*/
this.start = function start() {
var that = this; // 保存当前对象this
that.counter++;
that.taskId = setTimeout(function() {
that.start();
}, that.times);
if(that.task != null && typeof that.task === "function") {
that.task(that.counter);
}
};
/**
* 终止定时任务(模拟)
*/
this.stop = function() {
if(this.taskId != null && this.taskId != undefined) {
this.counter = 0;
clearTimeout(this.taskId);
}
};
/**
* 暂停定时任务(模拟)
*/
this.suspend = function() {
if(this.taskId != null && this.taskId != undefined) {
clearTimeout(this.taskId);
}
};
};
使用示例:
构造函数: 任务(function类型), 间隔时间( ms), 定时器名字
var timer = new TimerSimulator(function(count) {
console.log(“一秒钟输出一次!”);
}, 1000, “test”);
//启动
timer.start();
//停止
timer.stop();
//暂停
timer.suspend();