preface

Event Loop is a kind of operation mechanism of computer system, which is a very important concept. Javascript uses this mechanism to solve the problem of single-threaded running. This familiarity will make it easier to understand Vue’s asynchronous events.

More quality articles please pokeGitHubBlog, welcome to Star!!

JavaScript is single-threaded

1. What is single threading?

Single thread in program execution, the path of the program in sequential order, the first must be processed before the next can be executed. Simply put, you can only do one thing at a time.

2. Why is Js single threaded?

Js is a simple scripting language that runs on web pages. It was originally designed as a browser scripting language to interact with users and manipulate the DOM. This determines that it is single-threaded.

3. Problems with single threads?

Single-threaded means that all tasks need to be queued until the first one is finished before the next one can be executed. If the first task takes a long time, the second task will have to wait forever. This can lead to wasted performance when IO operations are time-consuming but CPU idle.

4. How to solve the performance problem of single thread?

It can be solved asynchronously. The main thread can suspend the waiting task and run the next task first, regardless of the IO operation. Wait until the IO operation returns the result, then go back and continue the pending task. Therefore, all tasks can be divided into two types, one is synchronous task, the other is asynchronous task.

Execution stack

As Javascript code executes, different variables are stored in different locations in memory: the heap and stack. There are some objects in the heap. The stack holds some basic type variables and Pointers to objects. But the execution stack we’re talking about here has a slightly different meaning than the one above.

To execute an executable script, js goes through the following steps:

  1. First, a global executable context is createdglobalContextEach time a function call is executed, an executable context is created.EC.
  2. An executable program may have many function calls, so many will be createdEC, soJavaScriptThe engine creates an Execution Context stack (ECS) to manage the Execution context.
  3. When the function call completes,JsExits the execution environment and destroys it, returning to the execution environment of the previous method. This process is repeated until all the code in the execution stack has been executed.

The instance

function fun3() {
    console.log('fun3')}function fun2() {
    fun3();
}
function fun1() {
    fun2();
}
fun1();
Copy the code

When a function is executed, an execution context is created and pushed onto the execution context stack. When the function is finished, the execution context of the function is ejected from the stack. With that in mind, let’s see what we can do with the code above:

1. Execute the global code, creating the global execution context, which is pushed into the execution context stack

ECStack = [
    globalContext
];
Copy the code
  1. Global context initialization
   globalContext = {
        VO: [global],
        Scope: [globalContext.VO],
        this: globalContext.VO
    }
Copy the code
  1. While I’m initializing,fun1The function is created to hold the internal properties of the scoped chain to the function[[scope]]
 fun1.[[scope]] = [
      globalContext.VO
    ];
Copy the code
  1. performfun1Function, createfun1Function execution context,fun1The function execution context is pushed into the execution context stack
 ECStack = [
        fun1,
        globalContext
    ];
Copy the code
  1. The fun1 function executes context initialization:

    1. Copy the function [[scope]] property to create the scope chain.

    2. Use arguments to create active objects.

    Initialize the active object, that is, add parameters, function declarations, variable declarations.

    4. Press the live object into the top of the FUN1 scope chain. At the same time the f function is created, saving the internal properties of the scope chain to the F function [[scope]]

  checkscopeContext = {
        AO: {
            arguments: {
                length: 0
            },
            scope: undefined,
            f: reference to function f(){}
        },
        Scope: [AO, globalContext.VO],
        this: undefined
    }
Copy the code
  1. performfun2()Function, repeat step 4.
  2. The resulting execution stack looks like this:
   ECStack = [
        fun3
        fun2,
        fun1,
        globalContext
    ];
Copy the code
  1. fun3After execution, pop from execution stack… All the way to thefun1

Event Loop

JavaScript memory model

Before understanding event loops, it is important to understand the Js memory model, which will help you understand event loops better.

  • Call Stack: Used for execution of main thread tasks.
  • Heap: Used to hold unstructured data, such as programmatically assigned variables and objects.
  • Task Queue: Stores asynchronous tasks.

Js asynchronous execution of the operation mechanism

  1. All synchronization tasks are executed on the main thread, forming an execution stack.
  2. In addition to the main thread, there is a task queue. Whenever an asynchronous task has a result, an event is placed in the task queue.
  3. Once all synchronization tasks in the execution stack have been executed, the system reads the task queue to see what events are in it. Those corresponding asynchronous tasks then end the wait state, enter the execution stack, and start executing.
  4. The main thread repeats step 3 above.

task

Asynchronous tasks are stored in the task queue, which can be divided into macrotasks and microtasks. Tasks registered by different APIS will enter their corresponding queues one by one, and then wait for the Event Loop to push them into the execution stack for execution.

Macro tasks mainly include:

  • script(Overall code)
  • setTimeout
  • setInterval
  • I/O,UIInteraction events
  • setImmediate(Node. Js environment)

Microtasks mainly include:

  • Promise
  • MutaionObserver
  • process.nextTick(Node. Js environment)

Our JavaScript execution process is single-threaded, and all tasks can be thought of as being stored in two queues — the execution queue and the event queue.

The execution queue is the task for all the synchronous code, the event queue is the macro task for all the asynchronous code, and our micro task is in between the two queues.

When JavaScript is executed, all synchronous codes will be executed first, and the corresponding asynchronous code will be stored in the corresponding queue according to its task type (macro task is put into the event queue, micro task is put into the execution queue, before the event queue). When the synchronous code is executed, the microtask between the execution queue and the event queue is executed, followed by the macro task in the event queue.

The instance

new Promise(resolve => {
    resolve(1);
    
    Promise.resolve().then(() => {
    	// t2
    	console.log(2)
    });
    console.log(4)
}).then(t => {
	// t1
	console.log(t)
});
console.log(3);
Copy the code

The flow of this code is roughly as follows:

  1. scriptTasks run first. The first encounterPromiseFor example, the constructor executes first, so 4 is printed first. At this timemicrotaskOf the taskt2t1
  2. scriptTask continues to run, output3. At this point, the first macro task is complete.
  3. Perform all microtasks and take them out in sequencet2t1, respectively output21
  4. Code execution complete

To sum up, the output of the above code is: 4321

Event loop

The main thread reads events from the task queue in a continuous Loop, so the whole operation mechanism is also called an Event Loop.

From the picture above, we can see that:

  • When the main thread runs, it generates heap and stack.
  • The code in the stack calls various external apis, which add various events (click, load, done) to the “task queue”.
  • When the stack completes, the main thread reads the task queue and executes the callback function corresponding to those events.

summary

The event loop is not that difficult, just look up more information and see more examples. Hope a little knowledge of children’s shoes to grasp the study.

Related articles

  • The Event Loop in JavaScript
  • Talk about the Event Loop
  • Let’s talk about JavaScript event loops in a nutshell
  • Introduction to the Event Loop mechanism