Home  >  Article  >  Web Front-end  >  An in-depth analysis of execution context and execution mechanism in JavaScript

An in-depth analysis of execution context and execution mechanism in JavaScript

青灯夜游
青灯夜游forward
2022-03-30 11:43:562439browse

This article will introduce you to threads and processes, and understand the execution context and execution mechanism in JavaScript. I hope it will be helpful to you!

An in-depth analysis of execution context and execution mechanism in JavaScript

About the execution context, execution stack, and execution mechanism (synchronous tasks, asynchronous tasks, microtasks, macrotasks, and event loops) in js The interview is a high-frequency test point, and some friends may be confused when asked, so the author will summarize it today, hoping it can be helpful to you in front of the screen. [Related recommendations: javascript learning tutorial]

Threads and processes

talk about the execution context and js execution in js Before the mechanism, let’s talk about threads and processes

What is a thread

In official termsThread is CPUThe smallest unit of scheduling.

What is a process

In official termsProcessisCPUResource allocation the smallest unit.

The relationship between threads and processes

Thread is a program run based on process Unit, a popular explanation Thread is an execution flow in the program. A process can have one or more threads.

There is only one execution flow in a process called single thread, that is, when the program is executed, the program paths taken are arranged in consecutive order, and the previous ones must be processed Okay, the rest will be executed.

Multiple execution streams in a process are called multithreads, that is, multiple different threads can be run simultaneously in one program. To perform different tasks, that is to say, a single program is allowed to create multiple threads executed in parallel to complete their respective tasks.

The author will give a simple example below. For example, if we open qqMusic to listen to music, qqMusic can be understood as a process. In qqMusic# In ## we can download while listening to music. This is multi-threading. Listening to music is a thread and downloading is a thread. If we open vscode again to write code, it will be another process.

Processes are independent of each other, but some resources are shared between threads under the same process.

The life cycle of a thread

The life cycle of a thread will go through five stages.

  • New state: After using the

    new keyword and the Thread class or its subclass to create a thread object, the thread object is in the new state. state. It remains in this state until the program start() this thread.

  • Ready state: When the thread object calls the

    start() method, the thread enters the ready state. The thread in the ready state is in the ready queue and can be run immediately as long as it obtains the right to use CPU.

  • Running state: If the thread in the ready state obtains the

    CPU resource, it can execute run(), and the thread is in the running state. . The thread in the running state is the most complex, it can become blocked, ready and dead.

  • Blocking state: If a thread executes

    sleep (sleep) , suspend (suspend) , wait (wait) and other methods, after losing the occupied resources, the thread will enter the blocking state from the running state. The ready state can be re-entered after the sleep time has expired or device resources have been obtained. It can be divided into three types:

    • Waiting blocking: The thread in the running state executes the

      wait() method to enter the waiting blocking state.

    • Synchronization blocking: The thread failed to acquire the

      synchronized synchronization lock (because the synchronization lock is occupied by other threads).

    • Other blocking: An

      I/O request was made by calling the thread's sleep() or join() , the thread will enter the blocking state. When the sleep() status times out, join() waits for the thread to terminate or times out, or I/O is processed, the thread re-enters the ready state.

  • Death state: When a running thread completes its task or other termination conditions occur, the thread switches to the terminated state.

An in-depth analysis of execution context and execution mechanism in JavaScript

Is js single-threaded or multi-threaded?

JS is single-threaded. JS As a browser scripting language, its main purpose is to interact with users and operate DOM. This determines that it can only be single-threaded, otherwise it will cause very complex synchronization problems. For example, suppose JavaScript has two threads at the same time. One thread adds content to a certain DOM node, and the other thread deletes the node. At this time, which thread should the browser use as the allow?

Execution context and execution stack

What is execution context

When the JS engine parses an executable code fragment (usually When it is the function calling stage), some preparatory work before execution will be done first. This "preparation work" is called "execution context (referred to as EC )" Or it can also be called execution environment.

Execution context classification

javascript There are three types of execution context, namely:

  • Global execution context This is the default or most basic execution context. There will only be one global context in a program, which will exist during the execution of the entire javascript script's life cycle. The bottom of the stack will not be destroyed by stack popping. The global context will generate a global object (taking the browser environment as an example, this global object is window), and bind the this value to this global object.

  • Function execution context Whenever a function is called, a new function execution context is created (regardless of whether the function is called repeatedly).

  • Eval function execution context The code executed inside the eval function will also have its own execution context, but because it is not often Use eval, so no analysis is done here.

What is the execution stack?

We mentioned earlier that js will create an execution context when running, but the execution context needs to be stored, so what is used to store it? You need to use the stack data structure.

The stack is a first-in, last-out data structure.

An in-depth analysis of execution context and execution mechanism in JavaScript

So in summaryThe execution context used to store the execution context created when the code is running is the execution stack.

js execution process

When executing a piece of code, the JS engine will first create an execution stack to store the execution context.

Then JS the engine will create a global execution context and push to the execution stack. In this process JS the engine will create a global execution context for this code All variables in allocate memory and assign an initial value (undefined). After the creation is completed, the JS engine will enter the execution phase. In this process, the JS engine will execute the code line by line, that is Assign values ​​(real values) to the variables that have been allocated memory one by one.

If there is a call to function in this code, then the JS engine will create a function execution context and push to the execution stack , its creation and execution process is the same as the global execution context.

When an execution stack is completed, the execution context will be popped from the stack, and then it will enter the next execution context.

The author will give an example below. If there is the following code in our program

console.log("Global Execution Context start");

function first() {
  console.log("first function");
  second();
  console.log("Again first function");
}

function second() {
  console.log("second function");
}

first();
console.log("Global Execution Context end");

Let’s briefly analyze the above example

  • First of all An execution stack will be created

  • Then a global context will be created and the execution contextpush will be added to the execution stack

  • Start execution, output Global Execution Context start

  • Encounter the first method, execute the method, create a function execution context andpushTo the execution stack

  • Execute first execution context, output first function

  • ##Encounter the

    second method, execute the method, create a function execution context and push to the execution stack

  • execute

    secondExecution context, outputsecond function

  • secondThe execution context is completed, popped from the stack, and enters the next execution ContextfirstExecution context

  • firstExecution context continues execution, outputAgain first function

  • firstAfter the execution of the execution context is completed, it is popped from the stack and enters the next execution context. Global execution context

  • Global execution context continues execution. Output

    Global Execution Context end

We use a picture to summarize

An in-depth analysis of execution context and execution mechanism in JavaScript

好了。说完执行上下文和执行栈我们再来说说js的执行机制

执行机制

说到js的执行机制,我们就需要了解js中同步任务和异步任务、宏任务和微任务了。

同步任务和异步任务

js中,任务分为同步任务和异步任务,那什么是同步任务什么是异步任务呢?

同步任务指的是,在主线程上排队执行的任务,只有前一个任务执行完毕,才能执行后一个任务。

异步任务指的是,不进入主线程、而进入"任务队列"的任务(任务队列中的任务与主线程并列执行),只有当主线程空闲了并且"任务队列"通知主线程,某个异步任务可以执行了,该任务才会进入主线程执行。由于是队列存储所以满足先进先出规则。常见的异步任务有我们的setIntervalsetTimeoutpromise.then等。

事件循环

前面介绍了同步任务和异步任务,下面我们来说说事件循环。

  • 同步和异步任务分别进入不同的执行"场所",同步的进入主线程,只有前一个任务执行完毕,才能执行后一个任务。异步任务不进入主线程而是进入 Event Table 并注册函数。

  • 当指定的事情完成时,Event Table 会将这个函数移入 Event QueueEvent Queue是队列数据结构,所以满足先进先出规则。

  • 主线程内的任务执行完毕为空,会去 Event Queue 读取对应的函数,进入主线程执行。

上述过程会不断重复,也就是常说的 Event Loop(事件循环)

我们用一张图来总结下

An in-depth analysis of execution context and execution mechanism in JavaScript

下面笔者简单来介绍个例子

function test1() {
  console.log("log1");

  setTimeout(() => {
    console.log("setTimeout 1000");
  }, 1000);

  setTimeout(() => {
    console.log("setTimeout 100");
  }, 100);

  console.log("log2");
}

test1(); // log1、log2、setTimeout 100、setTimeout 1000
  • 我们知道在js中会优先执行同步任务再执行异步任务,所以上面的例子会先输出log1、log2

  • 同步任务执行完后会执行异步任务,所以延迟100毫秒的回调函数会优先执行输出setTimeout 100

  • 延迟1000毫秒的回调函数会后执行输出setTimeout 1000

上面的例子比较简单,相信只要你看懂了上面笔者说的同步异步任务做出来是没什么问题的。那下面笔者再举一个例子小伙伴们看看会输出啥呢?

function test2() {
  console.log("log1");

  setTimeout(() => {
    console.log("setTimeout 1000");
  }, 1000);

  setTimeout(() => {
    console.log("setTimeout 100");
  }, 100);

  new Promise((resolve, reject) => {
    console.log("new promise");
    resolve();
  }).then(() => {
    console.log("promise.then");
  });

  console.log("log2");
}

test2();

要解决上面的问题光知道同步和异步任务是不够的,我们还得知道宏任务和微任务。

宏任务和微任务

js中,任务被分为两种,一种叫宏任务MacroTask,一种叫微任务MicroTask

常见的宏任务MacroTask

  • 主代码块

  • setTimeout()

  • setInterval()

  • setImmediate() - Node

  • requestAnimationFrame() - 浏览器

常见的微任务MicroTask

  • Promise.then()

  • process.nextTick() - Node

所以在上面的例子中就涉及到宏任务和微任务了,那宏任务微任务的执行顺序是怎么样的呢?

  • 首先,整体的 script(作为第一个宏任务)开始执行的时候,会把所有代码分为同步任务、异步任务两部分,同步任务会直接进入主线程依次执行,异步任务会进入异步队列然后再分为宏任务和微任务。

  • 宏任务进入到 Event Table 中,并在里面注册回调函数,每当指定的事件完成时,Event Table 会将这个函数移到 Event Queue

  • 微任务也会进入到另一个 Event Table 中,并在里面注册回调函数,每当指定的事件完成时,Event Table 会将这个函数移到 Event Queue

  • 当主线程内的任务执行完毕,主线程为空时,会检查微任务的 Event Queue,如果有任务,就全部执行,如果没有就执行下一个宏任务

我们用一张图来总结下

An in-depth analysis of execution context and execution mechanism in JavaScript

读懂了异步里面的宏任务和微任务上面的例子我们就可以轻易的得到答案了。

  • 我们知道在js中会优先执行同步任务再执行异步任务,所以上面的例子会先输出log1、new promise、log2。这里需要注意new promise里面是同步的

  • 主代码块作为宏任务执行完后会执行此宏任务所产生的所有微任务,所以会输出promise.then

  • 所有微任务执行完毕后会再执行一个宏任务,延迟100毫秒的回调函数会优先执行输出setTimeout 100

  • 此宏任务没有产生微任务,所以没有微任务需要执行

  • 继续执行下一个宏任务,延迟1000毫秒的回调函数会优执行输出setTimeout 1000

所以test2方法执行后会依次输出log1、new promise、log2、promise.then、setTimeout 100、setTimeout 1000

关于js执行到底是先宏任务再微任务还是先微任务再宏任务网上的文章各有说辞。笔者的理解是如果把整个js代码块当做宏任务的时候我们的js执行顺序是先宏任务后微任务的。

正所谓百看不如一练,下面笔者举两个例子如果你都能做对那你算是掌握了js执行机制这一块的知识了。

例子1

function test3() {
  console.log(1);

  setTimeout(function () {
    console.log(2);
    new Promise(function (resolve) {
      console.log(3);
      resolve();
    }).then(function () {
      console.log(4);
    });
    console.log(5);
  }, 1000);

  new Promise(function (resolve) {
    console.log(6);
    resolve();
  }).then(function () {
    console.log(7);
    setTimeout(function () {
      console.log(8);
    });
  });

  setTimeout(function () {
    console.log(9);
    new Promise(function (resolve) {
      console.log(10);
      resolve();
    }).then(function () {
      console.log(11);
    });
  }, 100);

  console.log(12);
}

test3();

我们来具体分析下

  • 首先js整体代码块作为一个宏任务最开始执行,依次输出1、6、12

  • 整体代码块宏任务执行完毕后产生了一个微任务和两个宏任务,所以宏任务队列有两个宏任务,微任务队列有一个微任务。

  • 宏任务执行完毕后会执行此宏任务所产生的的所有微任务。因为只有一个微任务,所以会输出7。此微任务又产生了一个宏任务,所以宏任务队列目前有三个宏任务。

  • 三个宏任务里面没有设置延迟的最先执行,所以输出8,此宏任务没有产生微任务,所以没有微任务要执行,继续执行下一个宏任务。

  • 延迟100毫秒的宏任务执行,输出9、10,并产生了一个微任务,所以微任务队列目前有一个微任务

  • 宏任务执行完毕后会执行该宏任务所产生的所有微任务,所以会执行微任务队列的所有微任务,输出11

  • 延迟1000毫秒的宏任务执行输出2、3、5,并产生了一个微任务,所以微任务队列目前有一个微任务

  • 宏任务执行完毕后会执行该宏任务所产生的所有微任务,所以会执行微任务队列的所有微任务,输出4

所以上面代码例子会依次输出1、6、12、7、8、9、10、11、2、3、5、4,小伙伴们是否做对了呢?

例子2

我们把上面的例子1稍作修改,引入asyncawait

async function test4() {
  console.log(1);

  setTimeout(function () {
    console.log(2);
    new Promise(function (resolve) {
      console.log(3);
      resolve();
    }).then(function () {
      console.log(4);
    });
    console.log(5);
  }, 1000);

  new Promise(function (resolve) {
    console.log(6);
    resolve();
  }).then(function () {
    console.log(7);
    setTimeout(function () {
      console.log(8);
    });
  });

  const result = await async1();
  console.log(result);

  setTimeout(function () {
    console.log(9);
    new Promise(function (resolve) {
      console.log(10);
      resolve();
    }).then(function () {
      console.log(11);
    });
  }, 100);

  console.log(12);
}

async function async1() {
  console.log(13)
  return Promise.resolve("Promise.resolve");
}

test4();

上面这里例子会输出什么呢?这里我们弄懂asyncawait题目就迎刃而解了。

我们知道asyncawait其实是Promise的语法糖,这里我们只需要知道await后面就相当于Promise.then。所以上面的例子我们可以理解成如下代码

function test4() {
  console.log(1);

  setTimeout(function () {
    console.log(2);
    new Promise(function (resolve) {
      console.log(3);
      resolve();
    }).then(function () {
      console.log(4);
    });
    console.log(5);
  }, 1000);

  new Promise(function (resolve) {
    console.log(6);
    resolve();
  }).then(function () {
    console.log(7);
    setTimeout(function () {
      console.log(8);
    });
  });

  new Promise(function (resolve) {
    console.log(13);
    return resolve("Promise.resolve");
  }).then((result) => {
    console.log(result);

    setTimeout(function () {
      console.log(9);
      new Promise(function (resolve) {
        console.log(10);
        resolve();
      }).then(function () {
        console.log(11);
      });
    }, 100);

    console.log(12);
  });
}

test4();

看到上面的代码是不是就能轻易得出结果呢?

  • 首先js整体代码块作为一个宏任务最开始执行,依次输出1、6、13

  • 整体代码块宏任务执行完毕后产生了两个微任务和一个宏任务,所以宏任务队列有一个宏任务,微任务队列有两个微任务。

  • 宏任务执行完毕后会执行此宏任务所产生的的所有微任务。所以会输出7、Promise.resolve、12。此微任务又产生了两个宏任务,所以宏任务队列目前有三个宏任务。

  • 三个宏任务里面没有设置延迟的最先执行,所以输出8,此宏任务没有产生微任务,所以没有微任务要执行,继续执行下一个宏任务。

  • 延迟100毫秒的宏任务执行,输出9、10,并产生了一个微任务,所以微任务队列目前有一个微任务

  • 宏任务执行完毕后会执行该宏任务所产生的所有微任务,所以会执行微任务队列的所有微任务,输出11

  • 延迟1000毫秒的宏任务执行输出2、3、5,并产生了一个微任务,所以微任务队列目前有一个微任务

  • 宏任务执行完毕后会执行该宏任务所产生的所有微任务,所以会执行微任务队列的所有微任务,输出4

所以上面代码例子会依次输出1、6、13、7、Promise.resolve、12、8、9、10、11、2、3、5、4,小伙伴们是否做对了呢?

扩展

setTimeout(fn, 0)

关于setTimeout(fn)可能很多小伙伴还是不太理解,这不明明没设置延迟时间吗,不应该立即就执行吗?

setTimeout(fn)我们可以理解成setTimeout(fn,0),其实是同一个意思。

我们知道js分同步任务和异步任务,setTimeout(fn)就是属于异步任务,所以这里就算你没设置延迟时间,他也会进入异步队列,需要等到主线程空闲的时候才会执行。

笔者这里再提一嘴,你觉得我们在setTimeout后面设置的延迟时间,js就一定会按我们的延迟时间执行吗,我觉得并不见得。我们设置的时间只是该回调函数可以被执行了,但是主线程有没有空还是另外一回事,我们可以举个简单的例子。

function test5() {
  setTimeout(function () {
    console.log("setTimeout");
  }, 100);

  let i = 0;
  while (true) {
    i++;
  }
}

test5();

上面的例子一定会在100毫秒后输出setTimeout吗,并不会,因为我们的主线程进入了死循环,并没有空去执行异步队列的任务。

GUI渲染

GUI渲染在这里说有些小伙伴可能不太理解,后面笔者会出关于浏览器的文章会再详细介绍,这里只是简单了解下即可。

由于JS引擎线程GUI渲染线程是互斥的关系,浏览器为了能够使宏任务DOM任务有序的进行,会在一个宏任务执行结果后,在下一个宏任务执行前,GUI渲染线程开始工作,对页面进行渲染。

所以宏任务、微任务、GUI渲染之间的关系如下

宏任务 -> 微任务 -> GUI渲染 -> 宏任务 -> ...

【相关视频教程推荐:web前端

The above is the detailed content of An in-depth analysis of execution context and execution mechanism in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete