The Event Loop is simple

preface

I have been working in the front end for three years, and I have never written any article about JavaScript, and I am not very clear about some underlying principles of JavaScript. Although I have had a general understanding of Event Loop, I can only understand it, but I cannot tell the underlying operating mechanism. Aware of my weak understanding of Event Loop, I decided to comprehensively analyze its operation mechanism. This article explains how the Event Loop works in the browser and when it executes. If anything is wrong, please point out my mistakes and I will correct them in time.

First we need to know two things:

  • JavaScript is a single-threaded language
  • Event Loop is the execution mechanism of JavaScript
JavaScript event loop

Before we understand JavaScript event loops, we need to know that JS is divided into synchronous and asynchronous code.

The synchronization task is executed on the main thread (i.e. the JS engine thread), forming an execution stack

In addition to the main thread, there is a task queue, and when the asynchronous task is finished running and the main thread is empty, an event callback is put into the task queue.

The asynchronous code is divided into macro tasks and micro tasks

  • Synchronous and asynchronous tasks enter different execution environments. Synchronous tasks enter the main thread and asynchronous tasks enter the Event Table and register functions
  • The Event Table adds this function to the Event Queue when the specified task is completed
  • When the main thread finishes executing, go back to the Event Loop to read the corresponding function and execute it in the main thread
  • This is called an Event Loop.

See here, must be some small partners still have some doubts

  • Which of the two tasks should be prioritized first

  • What does a specified event mean?

The execution sequence of macro and micro tasks

Answer first: perform macro tasks first, then micro tasks.

To clarify this problem, it is necessary to know that JS will register the functions of asynchronous tasks in the Event Table when executing synchronous code and encountering the code of asynchronous tasks.

For asynchronous tasks in Event Loop, macrotask events are placed in macroTask queue and microtask events are placed in microtask queue.

After the synchronous code of the main thread completes execution, the microtask queue of the code is detected and executed in first-in, first-out order.

After clearing the microtask queue, the macro task queue is also executed in first-in, first-out order.

Now, some of you might be confused about why the microtask queue is executed first and not the macro task queue.

The reason is that JavaScript running code is itself a macro task event.

What does a specified event mean

My understanding is the mission itself.

Asynchronous tasks are executed synchronously, and functions in asynchronous tasks are extracted and placed in the Event Table after execution.

Here’s an example:

	setTimeout( function task(){
	console.log('I am macrotask');
	},2000);
	requestAnimationFrame( function task(){
    	console.log('I am macrotask2');
	});
Copy the code

After the setTimeout function is executed, the task function of the parameter is placed in the Event Table, and the task function is placed in the MacroTask queue after the execution of setTimeout is completed after 2000ms.

The above code supports my guess because setTimeout takes up to 2000ms to complete and requestAnimationFrame executes before redrawing. So the printing order would be as follows

It should be added that, in our impression, setTimeout is at least 4ms

HTML Standard

  1. If timeout is less than 0, then set timeout to 0.
  2. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.
  3. Increment nesting level by one.
  4. Let task’s timer nesting level be nesting level.

It means:

If timeout is less than 0, set timeout to 0.

If the nesting level is greater than 5 and the delay is less than 4ms, set the minimum delay to 4ms.

However, in fact, the minimum time of setTimeout is different in different browsers, and it is not necessarily 4ms. Take Google for example, when the nesting level is less than 5, the minimum delay is 1ms; when the nesting level is greater than or equal to 5, the minimum delay is 4ms.

If you want to learn more, you can read this article

setInterval

The behavior of setInterval and setTimeout is not very different, except that setTimeout circulates functions into the Event Queue and waits if the main thread task is not finished.

It should be noted that if the delay time of setInterval is lower than the fn execution time of setInterval parameter, setInterval will not put Fn2 (we will name fn of the next loop fn2) into the Event Queue before fn execution is completed. This causes fn time to have no time interval at all;

So let’s do it. Let’s see how well do we know

    console.log('script start');
    new Promise((resolve, reject) = > {
        console.log('promise1')
        resolve()
    }).then(() = > {
        console.log('then 1')
    }).then(() = > {
        console.log('then 2')})Promise.resolve().then(() = > {
        console.log('promise2')})let _promise = () = > new Promise((resolve, reject) = > {
        console.log('promise3')})setTimeout(() = > {
        console.log('setTimeout1')
        Promise.resolve().then(() = > {
            console.log('promise4')})},100)
	setTimeout(() = > {
        console.log('setTimeout2')},0)
	_promise().then(() = > {
        console.log('then3')})console.log('script end');

Copy the code

The final output is:

**script start	promise1	promise3	script end	then 1	promise2	then 2	setTimeout2	setTimeout1	promise4**
Copy the code
conclusion

The above is my understanding of some existing articles on the Internet and after communicating with a friend. This article is my intensive reading and extension of ** article based on ** references [1].

Thank you for your reading, and thank you again for your communication and your predecessors’ articles. I suddenly understand the Event Loop, so THAT I can share with you.

subsequent

For those interested in learning more about the JS runtime mechanism, I recommend reading the article in Reference [4], which explains the browser’s js parsing process and how the JS runtime mechanism works with the browser’s various threads.

Author: juanfu

E-mail: 1390996852 @qq.com

References:

[1] Zhang Qian qianniuer JS Macro task/Micro Task based on Event Loop [OL]

[2] The Event Loop is an event loop. [OL]

[3] Weixin_48726650 Why setTimeout has a minimum delay of 4ms? [OL]

[4] “Core JS” to understand the RUNNING mechanism of JS [OL]

Ps: Putting a function into the event table is actually putting the function body into it as a callback function