A brief look at Web Workers

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')
myWorker.postMessage({foo: 'bar'})

Handling incoming messages inside a worker via onmessage

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

Terminating 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.

Sajad Torkamani

Hello! My name is Sajad. I’m a software developer at Nationwide and an aspiring entrepreneur. Originally from Afghanistan, I moved to London at an early age and have been living here for the past 20 years.

This is my personal website where I blog mostly about programming with occasional thoughts on a bunch of other things. I write mainly for my own benefit as I find that writing helps clarify my otherwise very confused thoughts.

Get in touch: sajadtorkamani1@gmail.com