最近遇到一个问题, 定时器每隔1秒发一次请求,要求本次请求成功后才能发下一次请求,需要把定时器弄成同步的
至于怎么弄成同步的,真是一把心酸泪呀
直接贴代码吧
```
<div style="height: 100px;width: 200px;float: right;">
<button id="btn">Clear Timer</button>
</div>
<script type="text/javascript">
var timer = {
timers:{},
start:function(asyn,fun,delay,id){
if(typeof fun === "function"){
var args = Array.prototype.slice.call(arguments,4),t,func,_this = this;
func = function(args){
var ags = arguments;
if(!Array.isArray) {
Array.isArray = function (vArg) {
return Object.prototype.toString.call(vArg) === "[object Array]";
};
}
if(!Array.isArray(args))
ags = Array.prototype.slice.call(arguments,0)
else
ags = args;
fun.apply(null,ags);
if(asyn){
console.log("asynchronous timer");
_this.timers[id] = setInterval(function(){
fun.apply(null,ags);
},delay);
}else{
console.log("synchronous timer");
_this.timers[id] = setTimeout(function(){
func.apply(null,ags);
},delay);
}
};
setTimeout(func,delay,args);
}
},
clear:function(id){
clearTimeout(this.timers[id]);
clearInterval(this.timers[id]);
delete this.timers.id;
}
};
function f1(p){
console.log("f1() : param1 : "+p+" , param2 : "+arguments[1] + " , param3 : "+arguments[2] + " " + new Date());
}
//test
//timer.start(true,f1,2000,"asyn","aa","bb","cc");
timer.start(false,f1,2000,"asyn","aa","bb","cc");
$("#btn").click(function(){
$.each(timer.timers,function(k,v){
console.log("key : "+k+" , v : "+v);
})
timer.clear("asyn")
});
</script>
```
同步的执行结果如下:
异步的执行结果如下: