JavaScript 定时器
说明: 原生的 setInterval 循环定时器在函数执行时间大于间隔时间时会出现执行间隔不均匀的现象,一般情况下我们想要的是在函数执行结束时开始算起,等待指定的间隔,再开始下一个函数的运行,也就是说函数的执行时间是不能计算在间隔时间内的,而 setInterval 和 setTimeout 第二个参数的时间指的是向队列添加新任务之前等 待的时间,因此只有执行时间短、非阻塞的回调函数比较适合 setInterval(),要兼容特殊情况的话我们只能用 setTimeout 加上闭包来代替 setInterval 实现循环定时的效果。
上代码:
class SetNewInterval {
constructor (obj = {
func: () => {},
time: 0,
autoStart: false,
jumpFirst: true
}) {
this.func = obj.func;
this.time = obj.time;
this.autoStart = obj.autoStart;
this.jumpFirst = obj.jumpFirst;
this.timer = null;
if (this.autoStart) {
this.start();
}
}
start () {
if (!this.jumpFirst) {
this.func();
}
let timeFunc = () => {
return setTimeout(() => {
this.func();
this.timer = timeFunc();
}, this.time);
}
this.timer = timeFunc ();
}
stop () {
clearTimeout(this.timer);
this.timer = null;
}
}
/**
* test
*/
let timeInter = new SetNewInterval({
func: () => {
console.log('123');
},
time: 1000,
autoStart: true,
jumpFirst: false
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论