Web Workers:
Keeping your JS apps animated
JS is single-threaded
- One call stack, one memory heap
- If a function takes long to execute, everything freezes

JS is asynchronous
- Event loop allows us to write async, non-blocking code
-
This is why fetch or setTimeout don't block the render
Jake Archibald - "In the Loop"
What does "blocking" mean?
- Code that occupies the thread
- Prevents or delays execution of code after it
while (true) {
console.log('To infinity and beyond!');
}
// Will never run!
extremelyImportantFunction();
The frame budget
Smooth animation means painting 60 frames per second
1000 ms / 60 frames = 16 ms/frame
Browser takes ~4 ms per frame to do work
All of our JS for each frame has to take ~12 ms or less
Web Workers
Run scripts in separate background thread, so that we don't block the main thread
Web Workers
- Runs JS code in a completely separate execution context
- Can communicate with main script using postMessage
- Messages can contain most basic JS data types, but not functions
- Data is copied, not shared (no shared memory)
- Workers can create new Workers
When to use Web Workers:
When to use
- CPU-intensive work
- Working with a lot of data
- Image processing
- Parallelizing tasks
- Frames are being dropped
- Games or lots of animations
When NOT to use
- I/O bound, not CPU bound
- i.e. if your constraint is network requests
- DOM manipulation
- When you expect shared memory
Helpful links
Web Workers API docs:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API
Comlink (awesome Web Workers library):
https://github.com/GoogleChromeLabs/comlink
react-app-rewired:
https://github.com/timarney/react-app-rewired
worker-loader:
Let's see Web Workers in action!
Thank you!
Questions? Ask me here or on Twitter!
Web Workers
By Mehdi Vasigh
Web Workers
- 225