Event Loop In Javascript

Surbhi Bhattar
4 min readMay 20, 2023
Photo by Mark Boss on Unsplash

It is a programming construct or design pattern that waits for and dispatches events or messages in a program. It makes use of two data structures — a call stack and a callback queue. Whenever call stack is empty, it removes a function from queue and pushes onto the stack. With the help of event loop, JS achieves asynchronous behaviour.

It is analogous to how traffic light works. Cars (Events) are managed by traffic police (JS Engine). When traffic light is green (call stack is empty), cars starts moving one after the other (similar to a queue).

Why should I care

If we don’t understand how JS execution works, then we might get unintended results for our code.

Ex. Let’s say a user is trying to login to our website, so we will follow below steps, i.e., we will ask them to enter their credentials, verify them, and show home page on success

const authenticate = () => {
console.log('Checking the credentials.. please wait!');
setTimeout(function (){
// time taking API call to check credentials
console.log('successfully verified!');
},3000);
}
console.log('Please enter your credentials');
authenticate();
console.log('Welcome!');

//Output:
//Please enter your credentials
//Checking the credentials.. please wait!
//Welcome!
//successfully verified!

Now here authenticate function takes some time to perform verification, but we see the welcome message shown before the user is verified. This is undesirable.

To solve this problem, we should make authenticate function return a promise and show welcome message upon promise settlement.

const authenticate = () => {
console.log('Checking the credentials.. please wait!');
return new Promise((resolve,reject)=>{
setTimeout(function (){
// time taking API call to check credentials
resolve('successfully verified!');
},3000);
})

}
console.log('Please enter your credentials');
authenticate()
.then(data => console.log(data+' Welcome!'))
.catch(err => console.log(err+' Wrong credentials.. please try again'))


//Output:
//Please enter your credentials
//Checking the credentials.. please wait!
//successfully verified! Welcome!

Check out my article on Promises to read more about them.

Event Loop explained

Components of web browser
  • Heap — Objects are allocated memory from here.
  • Stack — This represents the single thread provided for JavaScript code execution. Function calls form a stack of frames.
  • WebAPIs — These are built into the browser and not part of JS language.
  • Queue — After an API finishes execution, it is sent to the queue where it waits for its callback function execution.
  • Event Loop — checks whether stack is empty, if true then it picks one function from queue and places it on stack

Let’s take an example. Guess the output of following code snippet.

console.log('1');
setTimeout(function cb1(){
console.log('2');
},0);
console.log('3');

Did you guess correctly?

1
3
2

Let’s see pictorially how JS executes it

  1. The state is clear. The browser console is clear, and the Call Stack is empty.

2. console.log(“1”) is added to the stack

3. console.log(“1”) is executed and subsequently removed from the stack and setTimeout(function cb1(){…}) is added to the stack.

4. setTimeout(function cb1() { … }) is executed and removed from the stack. The browser creates a timer as part of the Web APIs. It is going to handle the countdown for you.

5. console.log(“3”) is added to the stack while the timer runs in the browser for cb1. Since the wait time is 0 ms, the callback will be added to queue as soon as the browser receives it (ideally)

6. console.log(“3”) is executed and removed from the stack. And cb1 is pushed to the queue.

7. The event loop checks that stack is empty now, so it takes cb1 from queue and pushes it to the stack. cb1 executes and adds console.log(“2”) onto the stack.

8. console.log(“2”) executes and is removed from the stack, then cb1 also completes execution is removed from the stack.

The delay argument in setTimeout() does not guarantee the start of execution after timer finishes the delay. It serves as a minimum time for the delay part.

References

Conclusion

In this article we have talked about event loop which is used by JS engine to execute code instructions. Event loop’s job is to check whenever call stack is empty, it will push a function from queue onto the stack. We have seen through an example how it will be executed by JS engine step by step.

--

--

Surbhi Bhattar

Web developer. Bibliophile. Amateur writer. Has a dream to write a bestselling book one day.