[ javascript ] Web Workers - 多執行緒

subtitle.terminate( )

Artis Tu
Artis Tu
Sep 1, 2018 · 2 min read

javascript 是單一執行緒( Single Thread )的語言,當有太多事情要處理的時候就會影響到畫面呈現,甚至整個卡住。

Web Workers 可以讓 javascript 用到其它執行緒。


檢查瀏覽器是否支援

為避免錯誤,可以用判斷式檢查瀏覽器是否支援 Web Wrokers:

Method

Web Workers 的架構不算太複雜,大致上有四個 method 要記住:

Worker() 用來創建 worker 物件
postMessage() 用來傳遞訊息
onmessage 用來接收訊息
terminate() 用來結束 worker,也可以在 worker 中使用 close() 將自己關掉。


實作

以下是一個小範例,由 main.js 傳 “Hello” 至 worker.js,將字串處理完之後再傳回 main.js 並且輸出( alert )。

執行完後瀏覽器會出現顯示 Hello World 的警告視窗。


使用限制

因為 Web Workers 屬於外部檔案,無法讀取以下內容:

window 物件
document 物件
parent 物件

因此像是 jQuery 這類跟 document 關聯性強的 library 就會無法使用。

Artis 的程式學習筆記

記錄日常所學

Artis Tu

Written by

Artis Tu

Artis 的程式學習筆記

記錄日常所學

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade