JS: Web Workers
2017-12-30 This page is work in progress. Ignore it.
What is Web Worker?
Web workers is a feature of browser that lets you run JavaScript process in the background in parallel.
JavaScript is single threaded. That is, all JavaScript code on a page run sequentially, including all even handler functions or setTimeout, setInterval. This is a problem, and Web workers is the solution.
Any task that requires heavy computation should run in a web worker, because otherwise it'll freeze browser.
Create Web Worker
let wk = new Worker("worker_script.js") // receive message from worker wk.onmessage = function (e) { console.log( "I'm main. I got this msg from worker: ", e.data) } // send message to worker wk.postMessage("hey worker, take this.")
The Worker Script
here's the worker_script.js:
console.log( "this worker is happily working.") // receive message from main onmessage = function (e) { console.log( "I'm worker. I got this msg from main: ", e.data ) } // send message to main postMessage("hey main, i need food.")
You can create many workers. 5 or 10 is typical. Worker can also create workers.
Terminate Worker
When done, you should terminate worker by:
WorkerObj.terminate()
Webworker also has a onerror property that can be useful.
WorkerObj.onerror()
Limitations
- Web worker does not have acccess to DOM. No
windowobject, nodocument,getElementByID, etc. - no acccess to parent page
but have
setTimeout,
setInterval,
XMLHttpRequest
importScripts()
determine, postMessage plain string or json