


Understand the execution context, execution stack, and event loop in JS
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.
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
Function
f
(*), 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 } } }
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).
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
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 theLexicalEnvironmentComponent
andVariableEnvironmentComponent 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
. 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
and set it towill 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 uninitialized - . The identifiers in
VarNames
are bound to
ObjRecand are directly initialized to
undefinedafter 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
: - 添加作业
task2
: - 添加作业
task3
:
执行到此处, task1
、task2
和task3
都被放入了任务队列; 然后执行栈全部执行完毕后,开始处理任务队列中的任务。
为什么任务队列中的任务必须在执行栈空时后执行呢?
- 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
andJava
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:
- Processing
task2
: - Processing
task1
: - Processing
task3
:
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 tutorialThe 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
