一、对setTimeout二次封装的原因
在项目中为了实现定时向后台发起请求,需要在每次ajax请求后,间隔几秒后再次向后台发起请求,如此循环往复。直接使用setTimeout也能实现这个功能,但是每次要写多行代码(麻烦)。
二、封装的Timeout的说明
- Timeout对象的属性如下:
属性值 | 描述 |
---|---|
timer | 用于存储setTimeout的计数,方便使用clearTimeout函数停止 |
time | 每次延时执行的时长 |
isStop | 标识是否继续执行setTimeout ,默认值false |
callback | 存储setTimeout执行的方法体 |
- Timeout对象的方法如下:
方法名 | 参数 | 描述 |
---|---|---|
start | callback:需要延时循环执行的函数 time:延时时长 exe:是否立即执行函数 | 初始化Timeout执行的函数和延时时长 |
open | 无 | 开启无限延时执行 |
stop | 无 | 停止无限延时执行 |
三、代码如下
// 延时计时器
function Timeout() {
this.timer = null;
this.time = '';
this.callback = '';
this.isStop = false;
}
// 开启计时器并添加
Timeout.prototype.start = function(callback, time, exe) {
// 查看isStop
if(exe == 'exe' && this.isStop) {
return;
}
// 先关闭计时器
this.stop();
this.isStop = false;
// 配置执行函数
if(typeof callback == 'function' && typeof time == 'number') {
this.callback = callback;
this.time = time;
if(exe != 'exe') {
callback();
}else {
this.isStop = false;
}
this.timer = setTimeout(callback, time);
}else {
console.warn('未完整配置参数!');
}
};
// 开启计时器
Timeout.prototype.open = function() {
var callback = this.callback;
var time = this.time;
this.start(callback, time, 'exe');
};
// 关闭计时器
Timeout.prototype.stop = function() {
this.isStop = true;
clearTimeout(this.timer);
};
// 使用方式
var timer = new Timeout();
function startTimer() {
timer.start(function() {
addNumber();
}, 1000);
}
function stopTimer() {
timer.stop();
}
var number = 1;
// 可以将timer.open();放到ajax执行成功后调用就实现了无限循环调用
function addNumber() {
number++;
console.log(number);
timer.open();
}