Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Loop into the Javascript Event Loop - JavaScript Israel Meetup

Loop into the Javascript Event Loop - JavaScript Israel Meetup

This short talk will explain how javascript handles being both single-threaded and non-blocking. We'll demystify the "Event Loop" and how concurrency works in javascript. If a coworker ever helped you solve a bug by wrapping a function with a `setTimeout(myFunc, 0)` and you felt cheated, this talk is definitely for you.

Presented at http://www.meetup.com/JavaScript-Israel/events/229643120/

cowchimp

March 30, 2016
Tweet

More Decks by cowchimp

Other Decks in Programming

Transcript

  1. Javascript is blocking for (var i = 0; i <

    10000000; i++) { }; var now = new Date().getTime(); while (new Date().getTime() < now + 10000) { }
  2. Can js operations be non-blocking? [ , , ] ,

    , , , , , , , , , , [ , , ] , , , , , , , , , , ,
  3. 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
  4. 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"
  5. • 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