setTimeout 和 setInterval 的用法

2017-03-15  本文已影响285人  kviccn

setTimeout

setTimeout() 方法设置一个定时器,该定时器在定时器到期后执行一个函数或指定的一段代码。

语法

let timeoutID = window.setTimeout(func[, delay, param1, param2, ...]);
let timeoutID = window.setTimeout(code[, delay]); 
let timeoutID = window.setTimeout(function, milliseconds);

说明:

需要注意的是,IE9 及更早的 IE 浏览器不支持第一种语法中向延迟函数传递额外参数的功能。如果你想要在 IE 中达到同样的功能,你必须使用一种兼容代码。

示例代码

setTimeout(() => console.log('text'), 1000) 
// text
setTimeout((text) => console.log(text), 1000, 'text') 
// text
setTimeout((...rest) => console.log(rest), 1000, 'text1', 'text2', 'text3') 
// ["text1", "text2", "text3"]
setTimeout(fn => fn('text'), 1000, console.log) 
// text
setTimeout((fn, text) => fn(text), 1000, console.log, 'text')
// text

setInterval

语法

let intervalID = window.setInterval(func, delay[, param1, param2, ...]);
let intervalID = window.setInterval(code, delay);

说明:

上一篇 下一篇

猜你喜欢

热点阅读