Web Workers

Multi-Threading In The Browser

cedpoilly

Freelance Web Developer

email
twitter.com/
facebook.com/
codementor.io/
linkedin.com/in/
cedpoilly@gmail.com
cedpoilly
cedpoilly
cedpoilly
cedpoilly

JavaScript
is Single-Threaded

But Good

At Concurrency

Concurrency

Multi-Tasking

Demo #0:
Expensive Async

 

AKA

Promise & setTimeout

<code>

Markup

Algorithm

Sync

Async

<goto demo>

Async is NOT free.

Demo #1:
Non-Locking

AKA

Parallelism

HOW???

Web Worker

Another Thread

HTML5

2009

Separate Thread

Message

Events

Runs In Parallel

From Main Thread

<NUMBERS>

60 frames / 1000 milliseconds
60frames/1000milliseconds60 frames / 1000 milliseconds
60 / 1000
60/100060 / 1000
1 frame = 1000/60
1frame=1000/601 frame = 1000/60
1 frame ~= 16 milliseconds
1frame =16milliseconds1 frame ~= 16 milliseconds

16 ms - 1 frame

That's not it!

DOM update:~8 ms

Main Thread: 8 ms

Web Worker APIs

  new Worker('worker.js')
  postMessage(message)
  onmessage

code?

Markup

Main Thread

Worker Thread

worker.js

Demo #2:
Multi-Purpose

AKA

Swiss Army Knife

Flux
Standard Action

as a
messaging protocol

 

Flux
Standard Action

as a
messaging protocol

 

algo: fibonacci

algo: sun

algo: expensive

APIs Recap

Instantiate a Worker

Send Messages

Back and Forth

Handle different messages

FSA

Demo #3:
Performance

AKA

"Divide and Conquer"

<code>

Inputs

Animation
& Ouput

Search
Algorithm

Queries: Main Thread

Queries: Worker

Worker Branching

Web Workers: Multithreading in the Browser

By Cedric Poilly

Web Workers: Multithreading in the Browser

After eight years of existence Web Workers are still underutilised. One cause might be the uncomfortable event-based APIs around the Worker interface. Giving up on multi-threading is a shame! Let's dive into the world of Web Workers and demystify the available APIs. The Web Worker is a tool each front-end developer deserves to have. Together let's have a look at some cases where workers are worth using. With some live coding we will prove that web apps can perform process intensive tasks in the browser. No native code needed.

  • 65