JavaScript Web Workers

Tobias Pfeiffer
Tobias PfeifferSoftware Engineer (Student) at Devolute
Multicore?
But isn't
that hard?
JavaScript Web Workers
JavaScript Web Workers
JavaScript Web Workers
Tobias Pfeiffer*
@PragTob
pragtob.wordpress.com
JavaScript Web Workers
Tobias Pfeiffer*
@PragTob
pragtob.wordpress.com
*with contributions from Tobias Metzke
JavaScript Web Workers
Multi-threaded
Share nothing
Not blocking the
main thread
Web Page
Create
Web Page
Web Page
A
B
Web Page
A
B
Send Message
Web Page
A
B
Work
Web Page
A
B
Answer
Web Page
A
B
Web Page
A
B
Web Page
A
B
What about
thread safety?
„The Worker interface spawns real OS-level threads, and
concurrency can cause interesting effects in your code if you
aren't careful. However, in the case of web workers, (...)it's
actually very hard to cause concurrency problems. (...) So you
have to work really hard to cause problems in your code.“
Mozilla Developer Network
JavaScript Web Workers
JavaScript Web Workers
Limitations
● Can not access the DOM
● High setup and memory cost
● Data may not contain functions or cycles
● Debugging
Getting to work
Starting a web worker
var worker = new Worker('worker_script.js');
Starting a web worker
var worker = new Worker('worker/counter.js');
Listening to the worker
var worker = new Worker('worker/counter.js');
worker.addEventListener('message', function(event){
// do stuff
});
Listening to the worker
var worker = new Worker('worker/counter.js');
worker.addEventListener('message', function(event){
$('#result').html(event.data);
});
Sending the worker messages
var worker = new Worker('worker/counter.js');
worker.addEventListener('message', function(event){
$('#result').html(event.data);
});
worker.postMessage(data);
Sending the worker messages
var worker = new Worker('worker/counter.js');
worker.addEventListener('message', function(event){
$('#result').html(event.data);
});
worker.postMessage({});
The Worker
var counter = 0;
self.onmessage = function(message) {
counter++;
self.postMessage(counter);
}
The Worker
var counter = 0;
self.onmessage = function(message) {
counter++;
self.postMessage(counter);
}
The Worker
var counter = 0;
self.onmessage = function(message) {
counter++;
self.postMessage(counter);
}
A Prime Number worker
findPrime = function(n) {
for (var i = 2; i <= Math.sqrt(n); i += 1) {
if (n % i == 0) {
return false;
}
}
return n;
}
self.onmessage = function(event) {
var num = parseInt(event.data);
self.postMessage(findPrime(num);
}
A Prime Number worker
findPrime = function(n) {
for (var i = 2; i <= Math.sqrt(n); i += 1) {
if (n % i == 0) {
return false;
}
}
return n;
}
self.onmessage = function(event) {
var num = parseInt(event.data);
self.postMessage(findPrime(num);
}
Importing Scripts in a worker
importScripts('script_path.js');
Background I/O
importScripts('io.js');
var timer;
var symbol;
function update() {
postMessage(symbol + ' ' + get('stock.cgi?' +
symbol));
timer = setTimeout(update, 10000);
}
onmessage = function (event) {
if (timer)
clearTimeout(timer);
symbol = event.data;
update();
};
Background I/O
importScripts('io.js');
var timer;
var symbol;
function update() {
postMessage(symbol + ' ' + get('stock.cgi?' +
symbol));
timer = setTimeout(update, 10000);
}
onmessage = function (event) {
if (timer)
clearTimeout(timer);
symbol = event.data;
update();
};
Background I/O
importScripts('io.js');
var timer;
var symbol;
function update() {
postMessage(symbol + ' ' + get('stock.cgi?' +
symbol));
timer = setTimeout(update, 10000);
}
onmessage = function (event) {
if (timer)
clearTimeout(timer);
symbol = event.data;
update();
};
Background I/O
importScripts('io.js');
var timer;
var symbol;
function update() {
postMessage(symbol + ' ' + get('stock.cgi?' +
symbol));
timer = setTimeout(update, 10000);
}
onmessage = function (event) {
if (timer)
clearTimeout(timer);
symbol = event.data;
update();
};
Listening for errors
worker.addEventListener('error', function(event){
// happy debugging
});
Use Cases
● Expensive non UI computations
● Handling big data
● Background I/O
● Ray Tracers
● AI
● …
● https://developer.mozilla.org/en-US/demos/tag/tech:webworkers/
Actors?
Actors
● Run in their own thread
● Do not share state
● Communicate via asynchronous
messages
JavaScript Web Workers
Web Workers
● Using modern multi core computers on
the client side
● Allow you to do the heavy lifting on the
client side
● Relatively easy to use
Resources
● Web Hypertext Application Technology Working Group. HTML
Specification - Web Workers.Website, 2013.
http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html
● Mozilla Developer Network. Using Web Workers. Website, 2013.
https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers
● MDN: Web Worker Demos
https://developer.mozilla.org/en-US/demos/tag/tech:webworkers
● Visualization from the end (don't use actor and actor2, use the others)
http://www.lively-kernel.org/repository/webwerkstatt/users/tmetzke/
Photo Credit
● Creative Commonts Attribution:
– http://www.w3.org/html/logo/downloads/HTML5_Logo.svg
– http://www.flickr.com/photos/klearchos/5580186619/
– http://www.flickr.com/photos/tedmurphy/8482500187/
● Creative Commons Attribution no derivative Works
– http://www.flickr.com/photos/49333775@N00/2383975585/
– http://www.flickr.com/photos/adplayers/5758743751/
● Creative Commons Attribution Share Alike
– http://www.flickr.com/photos/amatuer_44060/2831112854/
● Logos
– https://assets.mozillalabs.com/Brands-Logos/Firefox/logo-only/firefox_logo-only_RGB.png
– http://de.wikipedia.org/wiki/Datei:Internet_Explorer_9.svg
– https://en.wikipedia.org/wiki/File:Apple_Safari.png
– http://commons.wikimedia.org/wiki/File:Opera_O.svg
–
● Wikimedia Commons
– http://en.wikipedia.org/wiki/File:Chromium_11_Logo.svg
– http://en.wikipedia.org/wiki/File:Athlon64x2-6400plus.jpg
Photo Credit 2
● Creative Commons Attribution-No Derivs – No Commercial
– http://www.flickr.com/photos/cheesy42/8414666632/
1 of 50

More Related Content

What's hot(20)

Viewers also liked

Polyfill Web VRPolyfill Web VR
Polyfill Web VRBrameshmadhav S
582 views13 slides
Estudo 01Estudo 01
Estudo 01Renato Florentino
310 views14 slides

Viewers also liked(20)

Polyfill Web VRPolyfill Web VR
Polyfill Web VR
Brameshmadhav S582 views
Quick dive into WebVRQuick dive into WebVR
Quick dive into WebVR
Janne Aukia712 views
Firefox Extension DevelopmentFirefox Extension Development
Firefox Extension Development
phamvanvung2.6K views
Web vr creative_vrWeb vr creative_vr
Web vr creative_vr
Oscar Marin Miro549 views
Estudo 01Estudo 01
Estudo 01
Renato Florentino310 views
WebVR with Three.js!WebVR with Three.js!
WebVR with Three.js!
誠人 堀口571 views
WebVR -  JAX 2016WebVR -  JAX 2016
WebVR - JAX 2016
Carsten Sandtner757 views
Javascript the New PartsJavascript the New Parts
Javascript the New Parts
Federico Galassi20.9K views
Introduction to The VR WebIntroduction to The VR Web
Introduction to The VR Web
Liv Erickson743 views
20160713 webvr20160713 webvr
20160713 webvr
Noritada Shimizu1.3K views
Polyfill webVRPolyfill webVR
Polyfill webVR
Brameshmadhav S1.1K views
WebRTC: A front-end perspectiveWebRTC: A front-end perspective
WebRTC: A front-end perspective
shwetank7.6K views
Photo and photoPhoto and photo
Photo and photo
arreeluckdang332 views
Introduction to WebGL and WebVRIntroduction to WebGL and WebVR
Introduction to WebGL and WebVR
Daosheng Mu1.3K views

Similar to JavaScript Web Workers(20)

moblmobl
mobl
zefhemel904 views
A First Date With ScalaA First Date With Scala
A First Date With Scala
Franco Lombardo978 views
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury2.5K views
Introducing to node.jsIntroducing to node.js
Introducing to node.js
JeongHun Byeon2K views
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
Pascal Rettig2.2K views
Mobile webapplication developmentMobile webapplication development
Mobile webapplication development
Ganesh Gembali818 views
Web workers | JavaScript | HTML APIWeb workers | JavaScript | HTML API
Web workers | JavaScript | HTML API
pcnmtutorials160 views
Power ai image-pipelinePower ai image-pipeline
Power ai image-pipeline
Paulo Sergio Lemes Queiroz22 views
Google's HTML5 Work: what's next?Google's HTML5 Work: what's next?
Google's HTML5 Work: what's next?
Patrick Chanezon13.5K views
Why Node.jsWhy Node.js
Why Node.js
guileen2.9K views
Why Nodejs Guilin ShanghaiWhy Nodejs Guilin Shanghai
Why Nodejs Guilin Shanghai
Jackson Tian669 views
Scripting Oracle Develop 2007Scripting Oracle Develop 2007
Scripting Oracle Develop 2007
Tugdual Grall950 views
Testing for fun in production Into The Box 2018Testing for fun in production Into The Box 2018
Testing for fun in production Into The Box 2018
Ortus Solutions, Corp323 views

More from Tobias Pfeiffer(20)

Stories in Open SourceStories in Open Source
Stories in Open Source
Tobias Pfeiffer2.9K views
Functioning Among HumansFunctioning Among Humans
Functioning Among Humans
Tobias Pfeiffer3.3K views
Functioning Among HumansFunctioning Among Humans
Functioning Among Humans
Tobias Pfeiffer3K views
Elixir, your Monolith and YouElixir, your Monolith and You
Elixir, your Monolith and You
Tobias Pfeiffer3.5K views
 Where do Rubyists go?  Where do Rubyists go?
Where do Rubyists go?
Tobias Pfeiffer3.4K views
It's About the Humans, Stupid (Lightning)It's About the Humans, Stupid (Lightning)
It's About the Humans, Stupid (Lightning)
Tobias Pfeiffer2.1K views
Introducing Elixir the easy wayIntroducing Elixir the easy way
Introducing Elixir the easy way
Tobias Pfeiffer2K views

Recently uploaded(20)

Java Platform Approach 1.0 - Picnic MeetupJava Platform Approach 1.0 - Picnic Meetup
Java Platform Approach 1.0 - Picnic Meetup
Rick Ossendrijver23 views
Web Dev - 1 PPT.pdfWeb Dev - 1 PPT.pdf
Web Dev - 1 PPT.pdf
gdsczhcet48 views

JavaScript Web Workers

  • 5. JavaScript Web Workers Tobias Pfeiffer* @PragTob pragtob.wordpress.com
  • 6. JavaScript Web Workers Tobias Pfeiffer* @PragTob pragtob.wordpress.com *with contributions from Tobias Metzke
  • 21. „The Worker interface spawns real OS-level threads, and concurrency can cause interesting effects in your code if you aren't careful. However, in the case of web workers, (...)it's actually very hard to cause concurrency problems. (...) So you have to work really hard to cause problems in your code.“ Mozilla Developer Network
  • 24. Limitations ● Can not access the DOM ● High setup and memory cost ● Data may not contain functions or cycles ● Debugging
  • 26. Starting a web worker var worker = new Worker('worker_script.js');
  • 27. Starting a web worker var worker = new Worker('worker/counter.js');
  • 28. Listening to the worker var worker = new Worker('worker/counter.js'); worker.addEventListener('message', function(event){ // do stuff });
  • 29. Listening to the worker var worker = new Worker('worker/counter.js'); worker.addEventListener('message', function(event){ $('#result').html(event.data); });
  • 30. Sending the worker messages var worker = new Worker('worker/counter.js'); worker.addEventListener('message', function(event){ $('#result').html(event.data); }); worker.postMessage(data);
  • 31. Sending the worker messages var worker = new Worker('worker/counter.js'); worker.addEventListener('message', function(event){ $('#result').html(event.data); }); worker.postMessage({});
  • 32. The Worker var counter = 0; self.onmessage = function(message) { counter++; self.postMessage(counter); }
  • 33. The Worker var counter = 0; self.onmessage = function(message) { counter++; self.postMessage(counter); }
  • 34. The Worker var counter = 0; self.onmessage = function(message) { counter++; self.postMessage(counter); }
  • 35. A Prime Number worker findPrime = function(n) { for (var i = 2; i <= Math.sqrt(n); i += 1) { if (n % i == 0) { return false; } } return n; } self.onmessage = function(event) { var num = parseInt(event.data); self.postMessage(findPrime(num); }
  • 36. A Prime Number worker findPrime = function(n) { for (var i = 2; i <= Math.sqrt(n); i += 1) { if (n % i == 0) { return false; } } return n; } self.onmessage = function(event) { var num = parseInt(event.data); self.postMessage(findPrime(num); }
  • 37. Importing Scripts in a worker importScripts('script_path.js');
  • 38. Background I/O importScripts('io.js'); var timer; var symbol; function update() { postMessage(symbol + ' ' + get('stock.cgi?' + symbol)); timer = setTimeout(update, 10000); } onmessage = function (event) { if (timer) clearTimeout(timer); symbol = event.data; update(); };
  • 39. Background I/O importScripts('io.js'); var timer; var symbol; function update() { postMessage(symbol + ' ' + get('stock.cgi?' + symbol)); timer = setTimeout(update, 10000); } onmessage = function (event) { if (timer) clearTimeout(timer); symbol = event.data; update(); };
  • 40. Background I/O importScripts('io.js'); var timer; var symbol; function update() { postMessage(symbol + ' ' + get('stock.cgi?' + symbol)); timer = setTimeout(update, 10000); } onmessage = function (event) { if (timer) clearTimeout(timer); symbol = event.data; update(); };
  • 41. Background I/O importScripts('io.js'); var timer; var symbol; function update() { postMessage(symbol + ' ' + get('stock.cgi?' + symbol)); timer = setTimeout(update, 10000); } onmessage = function (event) { if (timer) clearTimeout(timer); symbol = event.data; update(); };
  • 42. Listening for errors worker.addEventListener('error', function(event){ // happy debugging });
  • 43. Use Cases ● Expensive non UI computations ● Handling big data ● Background I/O ● Ray Tracers ● AI ● … ● https://developer.mozilla.org/en-US/demos/tag/tech:webworkers/
  • 45. Actors ● Run in their own thread ● Do not share state ● Communicate via asynchronous messages
  • 47. Web Workers ● Using modern multi core computers on the client side ● Allow you to do the heavy lifting on the client side ● Relatively easy to use
  • 48. Resources ● Web Hypertext Application Technology Working Group. HTML Specification - Web Workers.Website, 2013. http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html ● Mozilla Developer Network. Using Web Workers. Website, 2013. https://developer.mozilla.org/en-US/docs/DOM/Using_web_workers ● MDN: Web Worker Demos https://developer.mozilla.org/en-US/demos/tag/tech:webworkers ● Visualization from the end (don't use actor and actor2, use the others) http://www.lively-kernel.org/repository/webwerkstatt/users/tmetzke/
  • 49. Photo Credit ● Creative Commonts Attribution: – http://www.w3.org/html/logo/downloads/HTML5_Logo.svg – http://www.flickr.com/photos/klearchos/5580186619/ – http://www.flickr.com/photos/tedmurphy/8482500187/ ● Creative Commons Attribution no derivative Works – http://www.flickr.com/photos/49333775@N00/2383975585/ – http://www.flickr.com/photos/adplayers/5758743751/ ● Creative Commons Attribution Share Alike – http://www.flickr.com/photos/amatuer_44060/2831112854/ ● Logos – https://assets.mozillalabs.com/Brands-Logos/Firefox/logo-only/firefox_logo-only_RGB.png – http://de.wikipedia.org/wiki/Datei:Internet_Explorer_9.svg – https://en.wikipedia.org/wiki/File:Apple_Safari.png – http://commons.wikimedia.org/wiki/File:Opera_O.svg – ● Wikimedia Commons – http://en.wikipedia.org/wiki/File:Chromium_11_Logo.svg – http://en.wikipedia.org/wiki/File:Athlon64x2-6400plus.jpg
  • 50. Photo Credit 2 ● Creative Commons Attribution-No Derivs – No Commercial – http://www.flickr.com/photos/cheesy42/8414666632/