JavaScript Event Loop
Tags: javascript, beginners, programming, tutorial
Published: 2022-01-01 21:37:11

## JavaScript single-threaded model
everyone knows that JavaScript is a single-threaded programming language. In other words, 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. JavaScript creates the execution contexts and pushes and pops functions onto and off the call stack in the execution process.

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 of the webpage, such as mouse click.

A blocking function can be a function that downloads a file from a remote server or calls an API from an external server.

### Example of blocking function

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

console.log('Start script...');
task('Download a file.');
console.log('Done!');
```
So what we have here is a big `while` loop inside the task() function to emulates a time-consuming task, the task() function is a blocking function, why ? because it takes a long time to complete.

And therefore the script will hangs for a few seconds (depending on how fast the computer is) and issues the following output

```js
Start script...
Download a file.
Done!
```
to execute the script, the JavaScript engine places the first call `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’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.

The following figure illustrates this

![Blocking Function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/749du6idwe6psfvmnc26.gif)

## Callbacks to the rescue
To prevent a blocking function from blocking other activities, you typically put it in a callback function for execution later

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

console.log('Start script...');

setTimeout(() => {
    task('Download a file.');
}, 1000);

console.log('Done!');
```
In this example, you’ll see the message `'Start script...'` and `'Done!'` immediately. And after that, you’ll see the message `'Download a file'`.

Here’s the output:

```js
Start script...
Done!
Download a file.
```
When you call the `setTimeout()` function, make a fetch request or click a button, the web browser can do these activities concurrently and asynchronously.

The `setTimeout()`, fetch requests, and DOM events are parts of the Web APIs of the web browser.

In our example, when you call the `setTimeout()` function, the JavaScript engine places it on the call stack, and the Web API creates a timer that expires in 1 second.

Then JavaScript engine place the task() function is into a queue called a callback queue or a task queue.


The following figure illustrates this

![Event Loop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q628qtq4gmwjalefu1qp.gif)

The event loop is a constantly running process that monitors both the callback queue and the call stack.

The event loop before move task() from the callback queue, first ask call stack if empty, if not the event loop waits until it is, however if empty then he moves task() to the call stack.

that's it for event loop, next post will be about hoisting

## Summary

In this post, you have learned about the JavaScript event loop, a constantly running process that coordinates the tasks between the call stack and callback queue to achieve concurrency.