setTimeout、setInterval被遗忘的第三个参数

一、最近在看promise,惊奇的发现:原来 setTimeout不只有两个参数,我还能说什么呢?赶紧探探究竟。

function multiply(input) {
    return new Promise(function (resolve, reject) {
        log('calculating ' + input + ' x ' + input + '...');
        setTimeout(resolve, 500, input * input);
    });
} 

二、定义

  • 扒了一下MDN,果然有定义:

    • Additional parameters which are passed through to the function specified by func once the timer expires.
      • 注:定时器启动时候,第三个以后的参数是作为第一个func()的参数传进去。

三、demo1

  • 增加两个参数

     function sum(x, y) {
         console.log(x+y)
     }
     setTimeout(sum, 1000, 1, 3);    //4
    
  • 增加三个参数 


    • (打印出的11是setTimeout的timeId)

    • 可以看出:

      • [第三个参数及以后的参数都可以作为sum函数的参数;]

四、再看demo2

  var doc=document.getElementById('div');
  setTimeout(function(){
      doc.style.color='red';
  },10000,setTimeout(function(){
      doc.style.color='black';
  },5000));
  • 上面的结果是,div元素内的字体样式5秒后变黑,10秒后再变红。是不是很惊奇,因为第三个参数也是一个定时器,5后就会开启。和JQuery里面的animate()不同,animate里面回调是执行了前面之后再执行后面的。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容