JS asynchronously

We already know that in the JS engine, we have an execution context stack. Each invocation of a function pushes more execution contexts into the execution stack.

There is another list in the JS engine, called the Event Queue. Naturally, it stores all the events or notifications of events that may be happening. For example, if have a ‘click’ event, it gets placed into this Event Queue.

Now, say we have multiple events going on, say we have a click event, and then an event for a HTTP request. They all get queued in this ‘Event Queue’.

The Event Queue gets looked at if the EXECUTION STACK IS EMPTY.

JS will then look at the queue. Say it sees a click event. And then goes to look for that handler to be invoked. It will then push an execution context for that handler onto the execution context.

Then then the next item in the queue moves up.

The browser may be asynchronously putting things into the event queue. However, the code that is running, is doing it synchronously.

Refresh the page. You’ll see your browser’s Activity Indicator scrolling. At this point, click the screen 4 times.

You’ll notice that nothing happens. This is because even though your events are placed into the Event Queue, it is not being processed. Instead, your code is being processed the Execution Context Stack. Specifically, the execution phase. It’s running your code where you have to wait 3 seconds.

When all of your code has been processed, it will log:
1) 3 seconds over
2) all done

Then it will continue onto the event queue. It will see the click events in there and process them one by one. Since it already has your handleEvent() in memory, it will invoke that function 4 times, and thus, you’ll see it display:

4 √ clicked

This is important because it means long-running functions that take up a lot of processing time can interrupt events being handled.