Skip to main content

[JS] setTimeout & setInterval

setTimeout & clearTimeout


setTimeout(func|code, [delay], [arg1], [arg2], ...)

Example

function sayHi(firstName, lastName) {
alert("Hello");
}

setTimeout(sayHi, 1000, "Bill", "Lin");

ClearTimeout

//clearTimeout 會回傳一個 'timerId',用來當作clearTimeout的argument
let timerId = setTimeout(...);
clearTimeout(timerId);


setInterval


let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...)

//clearInterval

clearInterval(timerId)




Running things regularly.

  1. setTimeout
  2. setInterval
//setInterval
let i = 1;
setInterval(function () {
func(i++);
}, 100);
//setTimeout
let i = 1;
setTimeout(function run() {
func(i++);
setTimeout(run, 100);
}, 100);

IMPORTANT: setTimeout 的時間區隔會比 setInterval 來的準確 因為 setInterval 的 func 執行也在設定的時間區隔之內,相法的,setTimeout 的時間區隔每一回都會重新計算。


https://javascript.info/settimeout-setinterval