sajad torkamani

What is a web worker?

A web worker is like a background thread that can run your JavaScript code in the background without affecting the current page by blocking other code.

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

Creating a worker

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

Sending messages to a worker via postMessage

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

Handling incoming messages inside a worker via onmessage

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

Terminating a worker


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