Reprinted: original link

What is an Event loop?

We start with a strange statement – although asynchronous JavaScript code is allowed (such as setTimeout ME), until ES6 JavaScript itself never actually had any direct asynchronous concepts built in. The JavaScript engine never does anything other than execute a single block of the program at any given moment.

So, who tells the JS engine to execute your block? In fact, the JS engine does not run in isolation, but in a hosted environment, which for most developers is a typical Web browser or Node.js. In fact, JavaScript is now embedded in everything from robots to light bulbs. Each individual device represents a different type of hosting environment for JS Engine.

Common in all environments is a built-in mechanism called an event loop, which handles the execution of multiple blocks in the program each time JS Engine is called

This means that the JS engine is just an on-demand execution environment for any arbitrary JS code. The timing of events (JS code execution) is the surrounding environment.

So, for example, when your JavaScript program makes an Ajax request to get some data from the server, you set the “response” code (” callback “) in the function, and the JS engine tells the hosting environment: “Hey, I’m suspending execution for now, but as soon as you complete the network request and have some data, please call this function back.”

The browser is then set up to listen for responses from the network, and when there is something that needs to be returned to you, the callback function is scheduled to execute by inserting it into the event loop. Let’s look at the picture below:

What are these Web apis? Essentially, they are threads that you can’t access and that you can call on. They are part of a browser that enables concurrency. If you’re a Node.js developer, these are ALL C ++ apis.

So what exactly is the event loop?

The event loop has a simple job – listening on the Call Stack and Callback Queue. If the Call Stack is empty, the Event Loop picks up the first Event from the Queue and pushes it onto the Call Stack, effectively running the Event. Such iterations are called tick in the event loop and each event is just a function callback.

console.log('Hi');
setTimeout(function cb1() { 
    console.log('cb1');
}, 5000);
console.log('Bye');
Copy the code

Let’s “execute” this code and see what happens:

  1. The state is clear. The browser console is cleared and the call stack is empty.

  1. Console.log (‘Hi’) is added to the call stack

  1. Console. log(‘Hi’) was executed.

  1. Console. log(‘Hi’) is removed from Call Stack.

  1. setTimeout(function cb1() { … }) is added to the Call Stack.

  1. setTimeout(function cb1() { … }). The browser will create timers as part of the Web API. It handles the countdown for you.

  1. setTimeout(function cb1() { … }) itself is complete and removed from the Call Stack.

  1. Console. log(‘Bye’) is added to the Call Stack. In the.

  1. The console. The log (‘ Bye ‘).

  1. Console. log(‘Bye’) is removed from the Call Stack.

  1. After at least 5000ms, the timer completes and the CB1 Callback is pushed to the “Callback Queue”.

  1. Event loop CB1 gets it from the Callback Queue and pushes it to the Call Stack.

  1. Cb1 executes and adds console.log(‘cb1’) to the Call Stack.

  1. The console. The log (‘ cb1).

  1. The console. The log (‘ cb1) from the Call Stack. Removed.

  1. Cb1 is deleted from the Call Stack.

A quick review:

Interestingly, ES6 specifies how the event loop works, which means that technically it falls within the responsibility of the JS engine, which is no longer just a host environment. One of the main reasons for this change was the introduction of Promises in ES6, because the latter requires access to direct, fine-grained control over scheduling operations on event loop queues (which we’ll discuss in more detail later)

SetTimeout (…). How it works

It is important to note that setTimeout(…) It does not automatically place the callback in the Event Loop Queue. It sets a timer. When the timer expires, the environment places your callback in the Event loop so that it can be selected and executed by a future tick. Take a look at this code:

setTimeout(myCallback, 1000);

This does not mean that myCallback will execute in 1,000 milliseconds, but rather that myCallback will add it to the Event Loop Queue in 1,000 milliseconds. However, the queue may also contain other events that were added earlier – your callback will have to wait.

Look at the following code:

setTimeout(function() {
    console.log('callback');
}, 0);
console.log('Bye');
Copy the code

Although the wait time is set to 0ms, the result in the browser console is the following:

Hi
Bye
callback
Copy the code