JavaScript 超时调用模拟间歇调用
JavaScript是单线程语言,所以在实际开发环境中,我们很少真正使用间歇调用方法,原因就是可能出现后一次调用会在前一次调用结束前启动,造成线程阻塞。
利用setTimeout()方法模拟间歇调用可解决这一痛点
/******模拟间歇调用******/
function SetIntervalPlus(fn,interval){
this.num = 0;
this.repeat;
this.fn = fn;
this.interval = parseInt(interval);
}
SetIntervalPlus.prototype = {
constructor: SetIntervalPlus,
start: function (){
this.num ++;
if(this.num == this.interval){
this.num = 0;
this.fn();
}
this.repeat = setTimeout(function(){
this.start();
}.bind(this),1000);//setTimeout方法默认把this对象指向window,利用bind()将this绑定到当前构造函数
},
stop: function (){
this.num = 0;
clearTimeout(this.repeat);
}
}
//使用方法
var updateCountNum = new SetIntervalPlus(function(){console.log("hello")},10);
updateCountNum.start();//开始
updateCountNum.stop();//停止
优点:保证方法执行完毕后才会开始下一次计时调用
缺点:当前方法只支持传入以秒为单位的整数,不支持毫秒级参数