在js里面怎么延时执行一个函数?一般利用setInterval,setTimeout进行延迟异步执行,或者利用while循环,sleep()进行同步阻塞。
这里有一篇写得挺好的博文,可能有助于对这个的理解,http://club.sm160.com/showtopic-931637.aspx
考虑到如果应用多次,可以针对Function全局对象进行扩展,为函数增加一个延时方法如delay,这样会让代码更简洁有效。
Function.prototype.delay = function(this1,timeout){
this1 = this1 || null;
timeout = timeout || 0;
var _this = this; // refer to function hi
var args = [];
console.log('delay is called');
switch(arguments.length){
case 1:
timeout = parseInt(arguments[0]);
timeout = isNaN(timeout)? 0 :timeout;
timeout = timeout<0 ? 0 :timeout;
break;
default:
for(var i=0;i<arguments.length;i++){
console.log('args['+i+']='+arguments[i]);
if(i>1) args.push(arguments[i]);
};
break;
};
var proxy = function(){
_this.apply(this1,args); //equals to xx1.hi(args)
};
return window.setTimeout(proxy,timeout);
};
var xx = function(n){
this.name = n;
};
xx.prototype.hi = function(a,b){
console.log('name='+this.name+'--'+a+'--'+b);
}
var xx1 = new xx('lgm');
var t = xx1.hi.delay(xx1,1000,"zj","jm");
xx1.hi("ilzj","iljm");
封装完这个之后,我又有了一个问题,setTimeout在后台是如何执行的?js的单线程又是如果执行的呢?
下面代码的执行结果又是什么呢?
setTimeout(function(){console.log("0")},0);
console.log("1");
setTimeout(function(){console.log("2")},3000);
setTimeout(function(){console.log("3")},1000);
setInterval(function(){console.log("4")},2000);
console.log("5");
输出 :1 5 0 3 4 2 4
其实这张图片能够很好地解析一切,假如是函数里面的命令,click命令跟(timer)setTimeout的命令同时到达,进队列的顺序按上图一样,那么就能够很好地解析那个例子了