Skip to main content
Home / Articles /

“Off The Main Thread”

JavaScript is what they call "single-threaded." As Brian Barbour puts it:

This means it has one call stack and one memory heap.

We all feel a symptom of that regularly in the form of performance jank and non-interactivity on elements or entire sites. If we give JavaScript lots of jobs and it gets really busy doing them, then it's not doing other things, like, say, handling our event handlers quickly.

There has been an interesting point/counter-point combo recently along these lines.

Das Surma has been advocating for moving as much JavaScript off the main thread as you possibly can. In fact, when it comes to using Web Workers, he suggests:

You should always use Web Workers.

Web Workers being the primary way to run JavaScript off the main thread.

There is lots to consider, of course, but I like how he compares this to how other languages call the main thread the "UI thread." If what you are doing is UI-related, do it on the main thread; if it's not, do it off the main thread. An example? State management.

David Gilbertson must have read that and wrote:

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread). Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

David's main point, it seems to me, is that some of the hefty JavaScript things we need to do are in response to user-initiated actions where the user needs to wait for things to finish anyway, so an unresponsive UI during that time is OK. But for anything that isn't user-initiated — and takes longer than say 100ms — he agrees a Web Worker is helpful.

(Looking at that 100ms thing, it's worth noting that a major point Das Surma is making is that the world is full of low-end phones — and who knows what 100ms on a high-end phone is when translated to on a low-end phone.)

icon-link icon-logo-star icon-search icon-star