筆記-JavaScript-event loop


Posted by mijouhsieh on 2021-10-28

「影片 Philip Roberts | JSConf EU | What the heck is the event loop anyway?」

快速複習:

  • 基本型別的保存方式,按值(by value),儲存的記憶體為stack memory,資料進出有順序。
  • 物件(陣列、物件...)的保存方式,按址(by reference),儲存在heap memory。

(MDN: JavaScript/EventLoop)


JavaScript 語言有什麼功能特性?

  • a single thread (wiki-單執行緒) (執行緒包含4種狀態: 產生spawn、阻塞block、非阻塞unblock、結束finish)
  • the heap 記憶體分配的地方。
  • a single call stack 呼叫堆疊、堆疊框架,為執行環境。一種資料結構,記錄當下在程式中哪個位置。
  • an event loop
  • a callback queue
  • some other APIs
  • single threaded Runtime
  • it can do one thing at a time.一次只做一件事。

JS Runtime的簡化示意圖
stack和heap的關係
-左側,各個函式、變數會先儲存在Heap記憶體(memory allocation)(無結構的區域)中,再執行程式。
-右側,Stack(堆疊)會先建立global execution context(全域執行環境),當有變數在global scope(全域)時,就會先被執行。
再依每一行程式碼執行動作,例如要執行function a 前,會在stack中建立 a() execution context,此時會在stack最上方,表示當下正在執行的程式碼,stack的底層仍有global execution context。 function a 執行完local scope(區域)後,a() execution context會離開stack --> 一次執行一個程式碼。
再換下個函式或是回到global execution context,執行在全域中的程式碼,最後程式碼都執行完後stack會清空。


動畫 Philip Roberts-how JavaScript's call stack/event loop/callback queue interact with each other.

Philip Roberts-how JavaScript's call stack/event loop/callback queue interact with each other.

程式碼如何執行?
網頁執行過程中是asynchrnous非同步的,而JS Engine是synchrnous同步的逐行執行程式碼。會先把stack中的execution context各種執行環境,能立即完成的先執行完,無法立即完成的(有callback function)移至callback queue的地方排列 (event queue事件佇列),等到stack都清空後,event loop就會把 callback queue內的東西放進stack中執行程式。


回到情境 倒數計時 setTimeout()

setTimeout(function(){console.log('delay 0 sec')}, 0)
console.log('Hello!')

stack會先執行global execution context,所以先印出Hello。
setTimeout在stack中建立 setTimeout() execution context,再執行程式碼,移至callback queue計時0秒後,event loop把程式碼送回stack印出delay 0 sec。


#javascript #Event Loop #stack







Related Posts

CSS 效能優化

CSS 效能優化

筆記:所有的函式都是閉包:談 JS 中的作用域與 Closure

筆記:所有的函式都是閉包:談 JS 中的作用域與 Closure

CH1 策略模式(Strategy Pattern)

CH1 策略模式(Strategy Pattern)


Comments