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) //3
}
setTimeout(sum, 1000, 1, 3);

增加三个参数 

(打印出的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里面回调是执行了前面之后再执行后面的。

 

 

  

posted @ 2017-05-08 23:55  leaf+  阅读(24039)  评论(2编辑  收藏  举报