Slide 1

Slide 1 text

Loop into the Javascript Event Loop

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

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

Slide 4

Slide 4 text

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 text

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

Slide 6

Slide 6 text

Technically…

Slide 7

Slide 7 text

Callbacks

Slide 8

Slide 8 text

Javascript Runtime Source: MDN Concurrency model and Event Loop

Slide 9

Slide 9 text

Javascript Runtime Ajax

Slide 10

Slide 10 text

Javascript Runtime Ajax result

Slide 11

Slide 11 text

Javascript Runtime Ajax callback

Slide 12

Slide 12 text

Javascript Runtime

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

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" `setTimeout` to the resuce

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

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

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

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'); Quiz time # 2 Source: Jake Archibald‘s "Tasks, microtasks, queues and schedules"

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

What about node.js?

Slide 23

Slide 23 text

• 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 Further reading

Slide 24

Slide 24 text

blog.cowchimp.com @cowchimp [email protected] Questions? Yonatan Mevorach