Loop into the Javascript Event Loop

A presentation at JavaScript Israel in March 2016 in Tel Aviv-Yafo, Israel by Yonatan Mevorach

Slide 1

Slide 1

Loop into the Javascript Event Loop

Slide 2

Slide 2

Yonatan Mevorach blog.cowchimp.com github.com/cowchimp @cowchimp

Slide 3

Slide 3

Javascript is single-threaded No race conditions, No locks. This is the life!

Slide 4

Slide 4

Javascript is blocking for (var i = 0; i < 10000000; i++) { }; var now = new Date().getTime(); while (new Date().getTime() < now + 10000) { }

Slide 5

Slide 5

js is blocking, everything else isn’t Ajax! Animations! Timeouts! User interactions!

Slide 6

Slide 6

Technically…

Slide 7

Slide 7

Callbacks

Slide 8

Slide 8

Javascript Runtime Source: MDN Concurrency model and Event Loop

Slide 9

Slide 9

Javascript Runtime Ajax

Slide 10

Slide 10

Javascript Runtime Ajax result

Slide 11

Slide 11

Javascript Runtime Ajax callback

Slide 12

Slide 12

Javascript Runtime

Slide 13

Slide 13

The Event Loop while (queue.waitForMessage()) { queue.processNextMessage(); }

Slide 14

Slide 14

Can js operations be non-blocking? [, , [ , , , , , , , , , , , , , , , , , , ] , , , , , ,]

Slide 15

Slide 15

setTimeout to the resuce function chunk(array, process, context) { var items = array.concat(); //clone the array setTimeout(function () { var item = items.shift(); process.call(context, item); if (items.length > 0) { setTimeout(arguments.callee, 100); } }, 100); } Source: Nicholas C. Zakas' "Timed array processing in JavaScript"

Slide 16

Slide 16

“Asyncify”™ sync operations setTimeout(myFunc, 0);

Slide 17

Slide 17

“Asyncify”™ sync operations setTimeout(myFunc, 0); setImmediate(myFunc); DEMO

Slide 18

Slide 18

“Asyncify”™ sync operations setTimeout(myFunc, 0); setImmediate(myFunc); https://github.com/YuzuJS/setImmediate requestAnimationFrame(myFunc); requestIdleCallback(myFunc); process.nextTick(myFunc); window.addEventListener("message", myFunc); Promise.resolve().then(myFunc);

Slide 19

Slide 19

Quiz time setTimeout(function () { console.log('hello'); }, 0); ['world'].forEach(function (str) { console.log(str); }); console.log('!');

Slide 20

Slide 20

Quiz time # 2 console.log('script start'); setTimeout(function () { console.log('setTimeout'); }, 0); Promise.resolve().then(function () { console.log('promise1'); }).then(function () { console.log('promise2'); }); console.log('script end'); Source: Jake Archibald‘s "Tasks, microtasks, queues and schedules"

Slide 21

Slide 21

Web Workers var myWorker = new Worker('worker.js');

Slide 22

Slide 22

What about node.js?

Slide 23

Slide 23

Further reading • What the heck is the event loop anyway? • Writing a Non-blocking JavaScript Quicksort • The case for setImmediate() • Dissecting the HTML 5 Event Loop - Loops, Task Queues and Tasks • The Basics of Web Workers

Slide 24

Slide 24

Questions? Yonatan Mevorach blog.cowchimp.com @cowchimp yonatan@sears.co.il