setTimeout 与 setInterval

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的回调可能被不停的执行,中间没间隔
(如果回调执行的时间超过预定等待的值)

 

    // 天亮了
    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

 

posted @ 2019-04-24 18:45  justSmile2  阅读(100)  评论(0编辑  收藏  举报