返回課程

setTimeout 會顯示什麼?

重要性:5

在以下程式碼中,有一個已排程的 setTimeout 呼叫,然後執行一個繁重的運算,需要花費超過 100 毫秒才能完成。

已排程的函式何時會執行?

  1. 迴圈之後。
  2. 迴圈之前。
  3. 迴圈開始時。

alert 會顯示什麼?

let i = 0;

setTimeout(() => alert(i), 100); // ?

// assume that the time to execute this function is >100ms
for(let j = 0; j < 100000000; j++) {
  i++;
}

任何 setTimeout 都會在目前程式碼執行完畢後才會執行。

i 會是最後一個:100000000

let i = 0;

setTimeout(() => alert(i), 100); // 100000000

// assume that the time to execute this function is >100ms
for(let j = 0; j < 100000000; j++) {
  i++;
}