Understanding Event Loops in JavaScript

Understanding Event Loops in JavaScript

Mastering Asynchronous Programming in JavaScript

Tiffany Kanyingi's photo
·

2 min read

The Event loop constantly monitors the state of the call stack and the callback queue. If the stack is empty, it will grab a callback from the callback queue and put it onto the call stack, scheduling it for execution.

The Call Stack keeps track of where we are in the code. It uses first in and last out and stacks for example functions.

The Callback queue stores the callback functions sent from the Web APIs in the order in which they were added. This queue is a data structure that runs in FIFO order.

FIFO ORDER – First In and First Out.

EXAMPLES OF EVENT LOOPS :

Run-to-completion - Each message is processed completely before any other message is processed.

Adding messages - In web browsers, messages are added anytime an event occurs and there is an event listener attached to it.

•The first two arguments to the function setTimeout are a message to add to the queue and a time value (optional; defaults to 0).

•Time value refers to the minimum delay time value represents the (minimum) delay after which the message will be pushed into the queue

• If there is no other message in the queue, and the stack is empty, the message is processed right after the delay.

•However, if there are messages, the setTimeout message will have to wait for other messages to be processed. For this reason, the second argument indicates a minimum time — not a guaranteed time.

•If there is no listener, the event is lost. So a click on an element with a click event handler will add a message — likewise with any other event.

EXAMPLE OF SETTIMEOUT :

Here is an example that demonstrates this concept (setTimeout does not run immediately after its timer expires)

ZERO DELAY

Zero delay doesn't mean the call back will fire-off after zero milliseconds. Calling setTimeout with a delay of 0 (zero) milliseconds doesn't execute the callback function after the given interval.

The execution depends on the number of waiting tasks in the queue.

The setTimeout needs to wait for all the code for queued messages to complete even though you specified a particular time limit for your setTimeout.