setTimeout 与 setInterval 实现回调本质上区别:
setTimeout(function(){
/* Some long block of code ... */
setTimout(arguments.callee,10);
},10);
setInterval(function(){
/* Some long block of code ... */
},10);
setTimeout代码至少每隔10ms以上才执行一次;
所以:如果一个计时器被阻塞执行,它将会延迟,直到下一个可执行点
(这可能比期望的时间更长)
setInterval固定每隔10ms将尝试执行,不管它的回调函数的执行状态。
所以:setInterval的回调可能被不停的执行,中间没间隔
(如果回调执行的时间超过预定等待的值)

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。 setTimeout 与 setInterval 随笔 第1张
    // 天亮了
    var fade = function (node) {
      var level = 1;
      var hex = level.toString(16);
      var step = function () {
        hex = level.toString(16);
        node.style.backgroundColor = "#" + hex + hex + hex;
        if (level < 15) {
          level++;
          setTimeout(step, 60);
        } else {
          console.log("End");
        }
      }
      step();
    }
    console.time('time');
    fade(document.body);
    console.timeEnd('time');
View Code

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄