R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

{Event Loop}

Did You Know?!

  • The JS engine does not run in isolation; it runs inside a hosting environment, which is for most developers the typical web browser
  • JS has expanded beyond the browser into other environments (such as servers) via platforms and run-time environments like Node.js
  • Notably though, Javascript is single-threaded which means it can only do one thing at a time
  • But wait! How does this work with asynchronicity...?

Did You Know?!

  • APIs and host environments handle asynchronous behavior and tell the Javascript environment when something is finished via the event loop/event queue
  • These mechanisms handle executing multiple chunks of your program over time
  • In other words, the JS engine has no innate sense of time, but is instead an on-demand execution environment for any arbitrary snippet of JS (i.e. 'events').

Example

  • When your JS program makes an AJAX request to fetch some data from a server, you set up the "response" code in a function (commonly called a "callback"), and with this the JS engine tells the hosting environment
    • "Hey, I'm suspending execution for now, but when you finish that that network request and you have some data, please call this function back."
  • At this point, the browser is set up to listen for the response from the network, and when it has something it schedules the callback function to be executed by inserting it into the event loop of the JS engine

Problem

  • The event loop is how the browser manages asynchronicity. Understanding how it works means you understand the environment you are working in.


  • Implement code that mimics how the event loop works. 
  • Don't get lost in the details, but simply try to capture its main functionality

Solution Code

// To implement the 'eventQueue' you can use an array 
// be sure to mimic a queue by only using '.shift()'
let eventQueue = [ ];

// ensure the event loop keeps going "forever"
while (true) {
    // perform a "tick"
    if (eventQueue.length > 0) {
        // get the next event in the queue
        let event = eventQueue.shift();

        // now, execute the next event
        //this try/catch block does all of the checks to ensure 
        //that the event is a function that can run appropriately
        try {
            event();
        }
        catch (err) {
            reportError(err);
        }
    }
}

//You can, but do not need to mimic pushing to the eventQueue

Resources

  1. Amazing lecture on the V8 event loop
  2. The visualization website that he made for the above lecture
  3. Solution code: repl.it

YDKJS: Event Loop

By Kate Humphrey

YDKJS: Event Loop

Technical interview problem on generating string permutations

  • 1,013