Home  >  Article  >  Web Front-end  >  Understand the execution context, execution stack, and event loop in JS

Understand the execution context, execution stack, and event loop in JS

青灯夜游
青灯夜游forward
2020-07-06 10:39:172013browse

This article takes you through the execution context, execution stack, and event loop in Javascript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Understand the execution context, execution stack, and event loop in JS

The following concepts, whether they are execution context or execution stack, are very abstract in the specification. , the understanding of many contents actually relies on imagination. If there are any mistakes, please correct me.

Execution Context

In short, execution context (Execution Context) is an abstraction of the environment in which the executable code is running. Used to trace the evaluation of variables in a block of code. This is a concept that I have summarized. It may be somewhat inaccurate. You can also refer to the real standard definition.

But in general, there are three key points:

  • Only executable code will have an execution context

  • Execution contexts are stateful: running state (Perform), suspend state (Suspend), and resume (Resume). The execution context in the Perfrom state is called the running execution context (Running Execution Context)

  • Execution context is not equivalent to the lexical environment at all, and the relationship is hard to say. It's just that the former quoted the latter.

  • When executing a JS script, there can be multiple execution contexts, but there is only one runtime context (the same is true for asynchronous, As for why four are mentioned...three Isn’t it common knowledge that there are four great kings...).

And ES specification stipulates that the executable codes are as follows:

  • Global code

  • Function code

  • Eval statement

  • Module code

In other words, look at the following code:

  
  var g=111
  function f(){
      
      console.log(g);
      for(let i =0; i <p> If the above code is run, only two execution contexts will be generated: </p>
  • global

  • Functionf

##But if you comment out the line marked

(*), then there will be only one execution context in the end, because function f will not be executed at all, and naturally there will be no corresponding execution context. The only confusing thing in it is that it is for-loop, but it is not executable code at all, so it is part of the function execution context.

Important components of execution context

An execution context can be abstracted as:

ExecutionContext = {
    State: 
    LexEnv = {
        This: ,
        OuterEnv: ,
        DecRec:{
            //... identifiername-variable
        }      
    }
    VaEnv = {
        This: ,
        OuterEnv: ,
        VarRec:{
            //... identifiername-variable
        }      
    }
}
In fact, there are two in an execution context Very important components:

LexicalEnvironmentComponent (lexical environment component) and VariableEnvironmentComponent (variable environment component). The lexical environment component points to the lexical environment (LexEnv) in current code, and the variable environment component points to the variable environment of current code (VarEnv).

A few things I have to say about

execution context, one very important part is the scope chain, but in execution context## No relevant content was seen in #. However, the scope chain does exist. It is in the [[Scope]] internal property and can be seen directly through the browser. But it can also be understood this way. When an execution context is created, not only the

LexEnv

of the current lexical environment will be created, but also LexEnv.OutEnv, ## will be created. #LexEnv.OutEnv.OutEnv… until it extends to the whole world. Creation and destruction of execution context

1. Create a new execution context (ExecutionContext, EC)

2. Create the current lexical environment (LexEnv and VarEnv)

3. Point the

LexicalEnvironmentComponent

and

VariableEnvironmentComponent of the execution context to the LexEnv and VarEnv## in the current environment. #middle. 4. Push the new execution context into the execution stack and become the

runtime execution context

. 5. Instantiate and initialize the identifiers within the executable code block:

Collect all declared identifiers in the current lexical environment

#Into
    DecRec
  • , all identifiers declared by

    var are included in the VarNames collection. At this stage, identifier names will be processed Detection, if the identifier declared with let/const/... is the same as the identifier in VarNames, an error will be reported. Instantiate the identifier in DecRec

    and set it to
  • uninitialized
  • . The identifiers in

    VarNames are bound to ObjRec and are directly initialized to undefined after instantiation.

  • 对于function声明的函数,将直接指向函数对象,并也会绑定到ObjRec中,这是浏览器默认行为

6、运行代码。

  • 非var声明的标识符会在声明处进行初始化(默认为undefined)。

  • 完成所有变量的赋值,并可能会一直在变化。

7、运行完毕从 执行栈 中弹出。

备注:

  • 关于This绑定,大部分情况可以用过去的说法解释,然而某些情况下却不尽然。
  • 闭包我会在下一篇介绍。
  • 执行上下文,我个人认为并不如何重要,但是却能在许多情形下起到极为关键的作用,所以还是有必要去深入认识一下。
  • 关于执行上下文和词法环境的关系,最多是前者引用了后者,仅此而已。诚然,有许多情况没必要用执行上下文来说明,但是永远避免不了违和感

执行栈与事件循环

执行栈(Execution Stack)就是由执行上下文构成的堆栈,类似于Call Stack

1、当Javascript引擎遇到一段可执行代码时,新建一个执行上下文。

2、将它推入执行栈中。并设置为运行时执行上下文。

  • 如果存在其他执行上下文。
  • 那么将当前执行上下文挂起
  • 然后再将新执行上下文推入执行栈中。

3、执行上下文运行完毕,弹出销毁恢复并将原执行上下文设为运行时。

总觉得这些没什么好说的,但是水一下吧

执行栈最重要的部分并非是执行栈概念本身,而是与任务队列的关系,它是事件循环的入门关键概念之一

众所周知,Javascript语言是单线程的,此处的执行栈就相当于主线程的调用栈,也是唯一一个调用栈,至于什么是主线程可以查阅相关资料,这里有些超纲了……

那么javascript是如何实现异步的

确切来说,这不是Javascript核心的部分,它是结合浏览器API(如Web Worker, Browser-context了解一下)实现的

事件循环中(事件处理过程),有两个极其重要的概念:

  • 任务序列: Task Quenue
  • 事件: Event

这两个概念,是抽象滴。

在Javascript中,一个任务也可以称之为事件,通常是一个函数回调,由许多任务组成的队列,就是所谓的任务序列了。任务序列有很多分类,例如:作业序列(Job Quenue)、消息序列(Message Quenue),本质没区别。

不必再深入了解,现在需要记住的是:一个任务序列中的任务如果想要被执行,就必须将它取出放入执行栈中。

举一个抽象点的例子:

例如下面的代码:

  
      var temp = 10;
      
      console.log('push task1');
      setTimeout(function task1(){
        temp+=10;
        console.log(temp+'task1 okay! ');
      },1000)
      
      console.log('taskquenue=[task1]; push task2');
      setTimeout(function task2(){
        temp*=10;
        console.log(temp+'task2 okay! ');
      },500) 
     
      console.log('taskquenue=[task1,task2]; push task3');
      setTimeout(function task3(){
        temp*= -0.2;
        console.log(temp+'task3 okay! ');
      },1500)
      console.log('taskquenue=[task1, task2,task3]');

输出如下:

push task1
taskquenue=[task1]; push task2
taskquenue=[task1,task2]; push task3
taskquenue=[task1, task2,task3]
100task2 okay! 
110task1 okay! 
-22task3 okay!

setTimeout是一个定时器,它能够将任务放到任务队列中。如图:

  • 添加作业task1
    Understand the execution context, execution stack, and event loop in JS
  • 添加作业task2
    Understand the execution context, execution stack, and event loop in JS
  • 添加作业task3
    Understand the execution context, execution stack, and event loop in JS

执行到此处, task1task2task3都被放入了任务队列; 然后执行栈全部执行完毕后,开始处理任务队列中的任务。

为什么任务队列中的任务必须在执行栈空时后执行呢?

  • I’m not sure here, after all, this really involves the underlying content; I just understand why it is like this, but I’m worried about misleading others, so forget it.
  • Generally speaking, the concepts related to Task Sequence are not so simple, and also involve many things, such as Blocking, Schedule(Schedule ), etc. For these aspects, you can refer to other multi-threaded languages ​​such as C and Java or look at the content of the operating system.
  • If it is just a simple business implementation, you don’t need to know so many underlying things.

Now start processing the task:

  • Processingtask2:
    Understand the execution context, execution stack, and event loop in JS
  • Processingtask1
    Understand the execution context, execution stack, and event loop in JS
  • Processing task3
    Understand the execution context, execution stack, and event loop in JS

Okay, an event loopThat’s it.
ThenJavascript engineenters the sleep phase(Javascript engine never ends!), waits for new tasks to be executed, and then starts the next event loop.

Remarks:
  • This is just a simple example
  • The event loop can have multiple task queues
  • Task sequence There are two types: microtask sequence and macrotask sequence
  • Our script code is one of the macrotask sequences.

Finally: Javascript engine

This is my Intensive Reading Javascript SeriesThe third article, I was caught off guardEvent Loop, it seems It goes into a lot of depth at once... But I think this is the most unreasonable programming arrangement. Most documents separate task sequence and call stack , but in ~~_____~~, they should be one, and they should not be separated for any convenient reason.

In-depth Javascript, in addition to reading the specifications, it is best to also read the implementation documents of the JS engine. Some advanced content is not in the specifications, but in these documents (please search it on Google , it can also be searched on Baidu).

If you are interested in Javascript engine, you can refer to:

  • MDN About_Javascript
  • Chromium V8 Reference
  • Github V8

Although, it is extremely not recommended for novices to look at the V8 source code all at once. The feeling of having a splitting headache and shaking all over is really enjoyable. …… Recommended related tutorials:

JavaScript video tutorial


The above is the detailed content of Understand the execution context, execution stack, and event loop in JS. For more information, please follow other related articles on the PHP Chinese website!

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