Web Workers - How are they different & why should we use them?

Let's sail two boats at a time, shall we?

ยท

4 min read

Since the birth of the mighty warrior who conquered the web as if it was nothing, now known as Javascript, there's a saying that has been going on ever since...

"Javascript is a synchronous and single-threaded programming language."

The majority of developers across the globe ๐ŸŒ would deny this and they should ๐Ÿ’ฏ. The concept of callbacks took out the synchronous nature of the language a long ago and now asynchronous programming in Javascript has evolved with the help of promises & async/await. Now we can, and let me quote it for you, perform non-blocking execution of code very easily in javascript.

But what about the other giant accusation of being a single-threaded language? ๐Ÿค”

That's where the Web Workers come into play. For detailed information about web workers, you can always refer to the MDN doc.

So what are Web Workers, you ask... huh?

Web workers provide a way to run scripts in the background on a separate thread (known as a worker thread).

Let's dig a little deeper... ๐Ÿคฉ

So you can create a worker object by using the Worker() constructor which takes a file path as an argument. This file contains all the logic that we want to execute on the worker thread.

let myAwesomeWroker = new Worker('worker.js')

This will spawn a new worker, that will execute the code written in worker.js on a separate thread.

Before you start scratching your heads ๐Ÿคฏ, here's why we need a separate thread...

If we just want to execute some piece of code in the background without blocking the main thread, we could've easily achieved that with promises. But there's a caveat, we know that asynchronous execution in JS is facilitated by Callback Queue & Event Loop. All the callbacks associated with an async function are pushed into a queue and the event loop keeps monitoring the call stack, a callback from the queue is picked by the event loop only when the call stack is empty ๐Ÿซ™, and put into the call stack.

Whoa! ๐Ÿ˜ฒ

Perhaps this might help...

So what if that task is a large computational task (that we returned as a promise ) and is resource intensive ๐Ÿ–ฅ๏ธ, in that case, the async method won't be efficient. Promise will take a substantial amount of time to resolve, and the associated callback will be picked up late causing higher latency ๐Ÿ™‡โ€โ™‚๏ธ.

So the right choice would be to execute that process separately, parallel with the other tasks being executed on the main thread.

This is often termed Multithreading.

Now that the cat's ๐Ÿฑ out of the bag ๐Ÿ‘œ, here's a layman's explanation of how asynchronous execution is different from multithreading .

  • Clark and Lois decide to make coffee โ˜•๏ธ but they don't have any milk ๐Ÿฅ›. So Lois says "You go whoosh โšก๏ธ in some milk from the store, and when you're back we'll make coffee together." - Async

  • Lois says "You go whoosh in some milk, I'll boil the water. While the water is boiling please grab some honey & sugar from the shelf, you can watch TV ๐Ÿ“บ while the coffee gets finished. Then we'll enjoy the coffee together." - Multithreading

Hope, that clears up things a bit.

Now what happens when the task on the worker thread is finished, how does the worker convey the response to the main thread? The communication b/w the main thread & worker thread happens via two event handlers that come with the package ๐Ÿ™Œ.

// sending messages to the worker
myAwesomeWorker.postMessage('Hey there, worker!')

// listening to the messages being emitted
myAwesomeWorker.onmessage = (e) => {
console.log("Here's what my worker has to say: ",e.data)
}

//NOTE: these two event handlers can be similarly used in the worker.js as well to send and listen to messages from main thread

But but but, is everything rainbows ๐ŸŒˆ and sunshine โ›…๏ธ about Web Workers?

No, there are certain limitations.

  • Workers have a separate global scope instead of the default global scope (window), so you can't access window or its methods inside of a worker.

  • We can't manipulate the DOM from a web worker, so no interference with the UI.

Here i've only touched the surface of Web Workers, there's more to them than this article. But that's what you amigos will discover, so wake up the Columbus inside you and start discovering (Well, not exactly countries ๐Ÿ˜… ).

Don't forget to drop your discoveries in the comment box below & if you really liked this article subscribe to my newsletter for more content like this.

Until then, Keep Cyberforming!!

ย