Scheduling: setTimeout and setInterval

setTimeout

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

// 1 秒後執行函式
function sayHi() {
  alert('Hello');
}
setTimeout(sayHi, 1000);

// 帶入參數到函式
function sayHi(phrase, who) {
  alert( phrase + ', ' + who );
}
setTimeout(sayHi, 1000, "Hello", "John"); // Hello, John

// 如果第 1 個參數是字串會視為函式,但不推薦
setTimeout("alert('Hello')", 1000);

// 這樣的寫法比較好
setTimeout(() => alert('Hello'), 1000);

// setTimeout 要帶入函式而非結果
// wrong!
setTimeout(sayHi(), 1000);

Canceling with clearTimeout

setInterval

Recursive setTimeout

透過 recursive setTimeout 每次延遲時間可以精準執行,setInterval 無法。

Garbage collection

setTimeout(…,0)

Splitting CPU-hungry tasks

Minimal delay of nested timers in-browser

Allowing the browser to render

Last updated

Was this helpful?