JS: Web Workers

By Xah Lee. Date: .

2017-12-30 This page is work in progress. Ignore it.

What's 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:

worker_obj.terminate()

Webworker also has a onerror property that can be useful.

worker_obj.onerror()

Limitations

but have setTimeout, setInterval, XMLHttpRequest

importScripts()

determine, postMessage plain string or json

Reference

Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog