preface

Recently, I came across an event loop problem while reading interview questions. I have heard about it from my friend before, but I haven’t had a thorough understanding of it.

After doing some research, it turned out to be a great thing!

What is an event loop?

Look at a picture first. It doesn’t matter if you don’t understand. Let me tell you all about it.

Heap: Objects are allocated in a heap, a computer term used to represent a large (usually unstructured) area of memory.

Stack: A function call forms a stack of frames.

WebAPIS: A reference to every API that encapsulates the powerful scripting capabilities of the Web, including the DOM, all related APIs, and related interfaces that can be used to build the Web.

Callback Queue: At some point during the event cycle, the runtime processes messages in the queue starting with the first message to be queued. The processed message is removed from the queue and the function associated with it is called as an input parameter.

– source MDN

Is it still not quite understand??

Okay, so let’s look at the code, which is asynchronous and synchronous.

setTimeout(() => {
    console.log(1)
}, 100)
console.log(2);
setTimeout(() => {
    console.log(3)
}, 0)
// 2
// 3
// 1
Copy the code

Demonstrate the code. This demo environment is a bit buggy, friends can write some other code to try, deepen understanding

SetTimeout (() => {console.log(1)}, 0) is executed in the Stack as an anonymous function in the WebAPIs, and is then placed in the Callback Queue. Console.log (2) is pushed directly into the Stack.

SetTimeout (() => {console.log(3)}, 0) The same execution will be put into the WebAPIs as an anonymous function and put into the Callback Queue. Methods in the Callback Queue Queue are pushed onto the Stack only after the synchronization task is complete.

Why is that?

Because JS is single-threaded, single-threaded means that all tasks need to be queued until the previous task finishes before the next task is executed. To solve the wait exclusion problem, JS tasks are divided into synchronous and asynchronous tasks. All synchronization tasks are executed on the main thread, forming a Stac. Asynchronous tasks (which go to WebAPI if they are WebAPI, such as Ajax setTimeout) do not go to the main thread, but to another Callback Queue. The synchronization tasks are executed in sequence. Only when the synchronization tasks in the execution stack are completed, the system reads back the asynchronous tasks that can be executed in the task queue, and then puts the asynchronous tasks from the event queue into the execution stack for execution. The cycle continues until all tasks are completed.

Source –

This is the Event Loop.

However, asynchronous tasks are divided into micro tasks and macro tasks!

What are microtasks and macrotasks?

At the end

The next article will cover microtasks and macrotasks.

Join the group to urge more…