The Magic of Event Loop

JavaScript is a single threaded language. This means it has one call stack and one memory heap. It executes code in the order and must finish executing a piece of code before moving onto the next.

JavaScript engine creates the global execution context before it starts to execute any code.
Global execution context holds information about the environment within which the current code is being executed.

Now let's see how stack works:

When the JavaScript engine first encounters your code, it creates a global execution context and pushes it to the stack. Whenever there is a function invocation, it creates a new execution context for that function and pushes it to the top of the stack.

The function's execution context which is at the top of the stack is executed first. When this function completes, its execution stack is popped off from the stack.

If you have a function that takes a long time to execute, it blocks all the interactions with web page such as mouse click. These functions are called blocking functions.

function task(message) {
   let n = 10000000000;
   while (n > 0){
      n--;
   }
console.log(message);
}
console.log('Start');
task('Run the task');
console.log('Done');

Output:

Start
Run the task
Done

In this example, we have a big while loop inside the task() function that runs a time-consuming task. The task() function is a blocking function.

The JavaScript engine first places the console.log() on top of the stack and executes it. Then, JavaScript places the task() function on top of the call stack and executes the function.

However, It take some time to complete the task() function. Therefore, you will see the message 'Run the task.' a little time later. After the task() function completes, the JavaScript engine pops it off the call stack.

Finally, the JavaScript engine places the console.log('Done') function on top of the stack and executes it.

This can we avoided with the help of Callback functions.

console.log('Start');
setTimeout(() => {
   task('Run the task');
}, 1000);

console.log('Done');

Output

Start
Done
Run the task

This asynchronous behavior is not part of the JavaScript language, But they are built on top of the JavaScript language in the browser and accessed through the Web APIs.

some examples of these async functions are setTimeout, setInterval, Event listeners etc.

The Magic of Event loop

The functions are pushed into the call stack in order. But the functions belonging to Web API's are sent to the browser to perform the task.
Meanwhile, the functions in callstack are executed without any delay. The functions which are executed by the browser are sent to Callback queue. The Event loop continuously check if the callstack is empty. If the callstack is empty, the functions in callback queue which are waiting to be executed are pushed into the callstack in order.

This is how the JavaScript runs asynchronous code without interrupting other activities.

Happy Learning!

25