js--延时执行

在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的命令同时到达,进队列的顺序按上图一样,那么就能够很好地解析那个例子了

转载于:https://www.cnblogs.com/lgmcolin/archive/2013/01/27/2878677.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值