JavaScript Event Loop

Summary: in this tutorial, you’ll learn about the event loop in JavaScript and how JavaScript achieves the concurrency model based on the event loop.

JavaScript single-threaded model

JavaScript is a single-threaded programming language. This means that JavaScript can do only one thing at a single point in time.

The JavaScript engine executes a script from the top of the file and works its way down. It creates the execution contexts and pushes and pops functions onto and off the call stack in the execution phase.

If a function takes a long time to execute, you cannot interact with the web browser during the function’s execution because the page hangs.

A function that takes a long time to complete is called a blocking function. Technically, a blocking function blocks all the interactions on the webpage, such as mouse clicks.

An example of a blocking function is a function that calls an API from a remote server. The following example uses a big loop to simulate a blocking function:

function task(message) {
    // emulate time consuming task
    let n = 10000000000;
    while (n > 0){
        n--;
    }
    console.log(message);
}

console.log('Start script...');
task('Call an API');
console.log('Done!');Code language: JavaScript (javascript)

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

The script hangs for a few seconds (depending on how fast the computer is) and issues the following output:

Start script...
Download a file.
Done!Code language: JavaScript (javascript)

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

However, it’ll take a while to complete the task() function. Therefore, you’ll see the message 'Download a file.' a little time later. After the task() function completes, the JavaScript engine pops it off the call stack.

Finally, the JavaScript engine places the last call to the console.log('Done!') function and executes it, which will be very fast.