Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

JavaScript Event Loop


Published on

Published in: Technology
  • Be the first to comment

JavaScript Event Loop

  1. 1. JavaScript Event LoopNot yo mama’s multithreaded
  2. 2. Who is Thomas Hunter?• Web developer for 8+ years• Dow, Ford, Quicken, Startup, Barracuda• Started development with PHP & MySQL• Became a Node.js fanboy• Writing a book on Backbone.js for Packt• @tlhunter |
  3. 3. What does MultiThreaded mean?• Makes use of separate CPU Cores as “Threads”• Uses a single process within the Operating System• True concurrency• Can have Race Conditions (simultaneous memory use)• “Hard” to get it right• Ran out of Ghz, hardware adds more cores
  4. 4. JavaScript is SingleThreaded• Makes use of a single CPU core• CPU intensive work is never “concurrent”• Easier to pull off, as in less technical difficulties
  5. 5. Technical Implementation• Stack:• Functions to run and available variables• More added as code is run• Stuff guaranteed to run in order• Heap:• “Chaotic” listing of objects• Queue:• Gets added to stack when stack empty• setTimeout and setInterval added hereCredit: Mozilla Developer Network
  6. 6. Example Code-runconsole.log("Adding code to the queue");setTimeout(function() { // Added somewhere in Heapconsole.log("Running next code from queue");}, 0);function a(x) { // Added somewhere in Heapconsole.log("a() frame added to stack");b(x);console.log("a() frame removed from stack");}function b(y) { // Added somewhere in Heapconsole.log("b() frame added to stack");console.log("Value passed in is " + y);console.log("b() frame removed from stack");}console.log("Starting work for this stack");a(42);console.log("Ending work for this stack");Adding code to the queueStarting work for this stacka() frame added to stackb()frame added to stackValue passed in is 42b() frameremoved from stacka() frame removed fromstackEnding work for this stackRunning next codefrom queue
  7. 7. Your App is Mostly Asleep• Node.js:All I/O is non-blocking• E.g. it gets thrown into the Queue• Browser:Wait for a click to happen• PHP:Wait for a MySQL query to run• These show how slow I/O can be →L1-Cache 3 cyclesL2-Cache14 cyclesRAM 250cyclesDisk 41,000,000Network 240,000,000
  8. 8. Sequential vs Parallel• Traditional web apps perform each I/O Sequentially• With an Event Loop, they can be run in Parallel• Since most time is wasted doing I/O, very inefficient
  9. 9. Non JS Event Loops• Event Loops can be implemented in other languages• However, JavaScript was built this way, feels “natural”• Examples:• Ruby: EventMachine• Python:Twisted & Tornado• PHP: ReactPHP
  10. 10. !JS Event Loop Examplesrequire eventmachinemodule Echodef post_initputs "Someone Connected"enddef receive_data datasend_data "#{data}"close_connection if data =~ /quit/ {EventMachine.start_server "", 8081, Echo}var net = require(net);var server = net.createServer(function (socket) {console.log(Someone Connected);socket.pipe(socket);});server.listen(1337,;EventMachine in Ruby Node.js
  11. 11. Event Loops are Awesome!• No race conditions• Typical web apps spend their time waiting on I/O• No funky syntax; it just works• Perform I/O operations “in parallel” easily• Stateful web applications are easy compared to PHP• Long run apps, don’t need web servers, shared data...
  12. 12. Event Loops aren’t Awesome!• CPU intensive work will block your process• You can offload work to different processes (Node.js)• It isn’t making use of those 8 cores you’ve got• You can use the Multi-node module though (Node.js)• Memory leaks are possible, not so with PHP• You can program better and prevent it though ;-)
  13. 13. Web Workers• You can use MultiThreaded JavaScript in your browser• IE10, Firefox 3.5, Chrome 4, Safari 4, Opera 10.6• var worker = new Worker(task.js);• Use Message Passing to share data• You share simple JSON data, not complex objects• Prevents deadlocks/race conditions because of this
  14. 14. Conclusion• Great for I/O bound applications (most web apps)• Horrible for CPU bound applications (do it in C ;)• Appears to be a single multi-threaded process• “Fakes” concurrency• @tlhunter