sajad torkamani

What is a web worker?

A web worker is like a background thread that lets you run JavaScript code in the background without blocking the main thread.

Workers can improve performance by allowing you to divide computationally expensive tasks among multiple workers, which can then perform those tasks on multi-processor cores.

Create a worker

// worker.js is the script that this worker will execute.
const myWorker = new Worker('worker.js')

Send messages to a worker via postMessage

myWorker.postMessage('foo')
myWorker.postMessage({foo: 'bar'})

Handle incoming messages inside a worker via onmessage

onmessage = (e) => {
  console.log(`Received some data: ${e.data}`)
  postMessage('Sending something back to main thread...')
}

Terminate a worker

myWorker.terminate()

Example usage of a worker

As a very trivial example, we could use a web worker to perform some complex arithmetic and then return the result back to the main page via the postMessage API when the computation has finished.

Tagged: JavaScript