Web Workers:

Keeping your JS apps animated

github: @mvasigh

twitter: @mehdi_vasigh

linkedin: @mehdi-vasigh

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"

www.youtube.com/watch?v=cCOL7MC4Pl0

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:

https://dassur.ma/things/when-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

 

Let's see Web Workers in action!

Thank you!

Questions? Ask me here or on Twitter!

github: @mvasigh

twitter: @mehdi_vasigh

linkedin: @mehdi-vasigh

Made with Slides.com