The purpose of this article is to ensure that you thoroughly understand the execution mechanism of javascript. If you still don’t understand after reading this article, you can beat me.
Whether you are a JavaScript novice or a veteran, whether you are interviewing for a job, or doing daily development work, we often encounter situations like this: given a few lines of code, we need to know its output content and order. Because javascript is a single-threaded language, we can draw the conclusion:
Readers will be beaten when they see this Lao: Don’t I know that js is executed line by line? Do you even need to say that? Be patient, because js is executed line by line, so we think js is like this:
let a = '1';console.log(a);let b = '2';console.log(b);复制代码
However, in fact js is Like this:
setTimeout(function(){ console.log('定时器开始啦') });new Promise(function(resolve){ console.log('马上执行for循环啦'); for(var i = 0; i < 10000; i++){ i == 99 && resolve(); } }).then(function(){ console.log('执行then函数啦') });console.log('代码执行结束');复制代码
According to the concept that js is executed in the order in which statements appear, I confidently wrote down the output results :
//"定时器开始啦"//"马上执行for循环啦"//"执行then函数啦"//"代码执行结束"复制代码
I went to chrome to verify it, and the result was completely wrong. I was confused for a moment. Did I execute it line by line as promised?
We really need to thoroughly understand the execution mechanism of javascript.
javascript is a single-threaded language. Web-Worker is proposed in the latest HTML5, but the core of javascript being single-threaded is still Unchanged. Therefore, all JavaScript versions of "multi-threading" are simulated with a single thread, and all JavaScript multi-threads are paper tigers!
Since js is single-threaded, it is like a bank with only one window. Customers need to queue up to handle business one by one. Similarly, js tasks must be executed one by one. . If one task takes too long, the next task will also have to wait. So here comes the question, if we want to browse news, but the ultra-high-definition pictures contained in the news load very slowly, does our webpage have to stay stuck until the pictures are fully displayed? Therefore, smart programmers divide tasks into two categories:
When we open the website, the rendering process of the web page It’s a bunch of synchronized tasks, such as the rendering of page skeletons and page elements. Tasks that take up a lot of resources and take a long time, such as loading pictures and music, are asynchronous tasks. There is a strict textual definition of this part, but the purpose of this article is to thoroughly understand the execution mechanism with the minimum learning cost, so we use a map to illustrate:
If the content of the map is expressed in words:
We can’t help but ask, how do we know that the main thread execution stack is empty? There is a monitoring process in the js engine, which will continuously check whether the main thread execution stack is empty. Once it is empty, it will go to the Event Queue to check whether there is a function waiting to be called.
Having said so many words, it would be more straightforward to write a piece of code:
let data = []; $.ajax({ url:www.javascript.com, data:data, success:() => { console.log('发送成功!'); } })console.log('代码执行结束');复制代码
The above is a simple ajax
request code:
success
. console.log('Code execution ends')
. success
enters the Event Queue. success
from the Event Queue and executes it. I believe that through the above text and code, you already have a preliminary understanding of the execution sequence of js. Next let's study the advanced topic: setTimeout.
The famous setTimeout
Needless to say, everyone’s first impression of it is that asynchronous execution can be delayed. We often In this way, a delay of 3 seconds is achieved:
setTimeout(() => { console.log('延时3秒'); },3000)复制代码
Gradually setTimeout
is used in more places, and problems arise. Sometimes the delay is clearly written to be 3 seconds, but the actual delay is 5 or 6 seconds. It takes seconds to execute the function, so what's going on?
先看一个例子:
setTimeout(() => { task(); },3000)console.log('执行console');复制代码
根据前面我们的结论,setTimeout
是异步的,应该先执行console.log
这个同步任务,所以我们的结论是:
//执行console//task()复制代码
去验证一下,结果正确!
然后我们修改一下前面的代码:
setTimeout(() => { task() },3000) sleep(10000000)复制代码
乍一看其实差不多嘛,但我们把这段代码在chrome执行一下,却发现控制台执行task()
需要的时间远远超过3秒,说好的延时三秒,为啥现在需要这么长时间啊?
这时候我们需要重新理解setTimeout
的定义。我们先说上述代码是怎么执行的:
task()
进入Event Table并注册,计时开始。sleep
函数,很慢,非常慢,计时仍在继续。timeout
完成,task()
进入Event Queue,但是sleep
也太慢了吧,还没执行完,只好等着。sleep
终于执行完了,task()
终于从Event Queue进入了主线程执行。上述的流程走完,我们知道setTimeout
这个函数,是经过指定时间后,把要执行的任务(本例中为task()
)加入到Event Queue中,又因为是单线程任务要一个一个执行,如果前面的任务需要的时间太久,那么只能等着,导致真正的延迟时间远远大于3秒。
我们还经常遇到setTimeout(fn,0)
这样的代码,0秒后执行又是什么意思呢?是不是可以立即执行呢?
答案是不会的,setTimeout(fn,0)
的含义是,指定某个任务在主线程最早可得的空闲时间执行,意思就是不用再等多少秒了,只要主线程执行栈内的同步任务全部执行完成,栈为空就马上执行。举例说明:
//代码1console.log('先执行这里'); setTimeout(() => { console.log('执行啦') },0);复制代码
//代码2console.log('先执行这里'); setTimeout(() => { console.log('执行啦') },3000);复制代码
代码1的输出结果是:
//先执行这里//执行啦复制代码
代码2的输出结果是:
//先执行这里// ... 3s later// 执行啦复制代码
关于setTimeout
要补充的是,即便主线程为空,0毫秒实际上也是达不到的。根据HTML的标准,最低是4毫秒。有兴趣的同学可以自行了解。
上面说完了setTimeout
,当然不能错过它的孪生兄弟setInterval
。他俩差不多,只不过后者是循环的执行。对于执行顺序来说,setInterval
会每隔指定的时间将注册的函数置入Event Queue,如果前面的任务耗时太久,那么同样需要等待。
唯一需要注意的一点是,对于setInterval(fn,ms)
来说,我们已经知道不是每过ms
秒会执行一次fn
,而是每过ms
秒,会有fn
进入Event Queue。一旦setInterval
的回调函数fn
执行时间超过了延迟时间ms
,那么就完全看不出来有时间间隔了。这句话请读者仔细品味。
传统的定时器我们已经研究过了,接着我们探究Promise
与process.nextTick(callback)
的表现。
Promise
的定义和功能本文不再赘述,不了解的读者可以学习一下阮一峰老师的Promise。而process.nextTick(callback)
类似node.js版的"setTimeout",在事件循环的下一次循环中调用 callback 回调函数。
我们进入正题,除了广义的同步任务和异步任务,我们对任务有更精细的定义:
不同类型的任务会进入对应的Event Queue,比如setTimeout
和setInterval
会进入相同的Event Queue。
事件循环的顺序,决定js代码的执行顺序。进入整体代码(宏任务)后,开始第一次循环。接着执行所有的微任务。然后再次从宏任务开始,找到其中一个任务队列执行完毕,再执行所有的微任务。听起来有点绕,我们用文章最开始的一段代码说明:
setTimeout(function() { console.log('setTimeout'); })new Promise(function(resolve) { console.log('promise'); }).then(function() { console.log('then'); })console.log('console');复制代码
setTimeout
,那么将其回调函数注册后分发到宏任务Event Queue。(注册过程与上同,下文不再描述)Promise
,new Promise
立即执行,then
函数分发到微任务Event Queue。console.log()
,立即执行。then
在微任务Event Queue里面,执行。setTimeout
对应的回调函数,立即执行。事件循环,宏任务,微任务的关系如图所示:
我们来分析一段较复杂的代码,看看你是否真的掌握了js的执行机制:
console.log('1'); setTimeout(function() { console.log('2'); process.nextTick(function() { console.log('3'); }) new Promise(function(resolve) { console.log('4'); resolve(); }).then(function() { console.log('5') }) }) process.nextTick(function() { console.log('6'); })new Promise(function(resolve) { console.log('7'); resolve(); }).then(function() { console.log('8') }) setTimeout(function() { console.log('9'); process.nextTick(function() { console.log('10'); }) new Promise(function(resolve) { console.log('11'); resolve(); }).then(function() { console.log('12') }) })复制代码
第一轮事件循环流程分析如下:
console.log
,输出1。setTimeout
,其回调函数被分发到宏任务Event Queue中。我们暂且记为setTimeout1
。process.nextTick()
,其回调函数被分发到微任务Event Queue中。我们记为process1
。Promise
,new Promise
直接执行,输出7。then
被分发到微任务Event Queue中。我们记为then1
。setTimeout
,其回调函数被分发到宏任务Event Queue中,我们记为setTimeout2
。宏任务Event Queue | 微任务Event Queue |
---|---|
setTimeout1 | process1 |
setTimeout2 | then1 |
上表是第一轮事件循环宏任务结束时各Event Queue的情况,此时已经输出了1和7。
我们发现了process1
和then1
两个微任务。
process1
,输出6。then1
,输出8。好了,第一轮事件循环正式结束,这一轮的结果是输出1,7,6,8。那么第二轮时间循环从setTimeout1
宏任务开始:
process.nextTick()
,同样将其分发到微任务Event Queue中,记为process2
。new Promise
立即执行输出4,then
也分发到微任务Event Queue中,记为then2
。宏任务Event Queue | 微任务Event Queue |
---|---|
setTimeout2 | process2 |
then2 |
process2
和then2
两个微任务可以执行。process.nextTick()
分发到微任务Event Queue中。记为process3
。new Promise
,输出11。then
分发到微任务Event Queue中,记为then3
。宏任务Event Queue | 微任务Event Queue |
---|---|
process3 | |
then3 |
process3
and then3
are executed. The entire code has been executed three event loops in total, and the complete output is 1, 7, 6, 8, 2, 4, 3, 5, 9, 11, 10, 12.
(Please note that the event monitoring in the node environment depends on libuv and the front-end environment is not exactly the same, and the output order may have errors)
We have said from the beginning that JavaScript is a single-threaded language. No matter what new framework or new syntax sugar implements the so-called asynchronous, it is actually simulated using synchronous methods. Keep a firm grasp of it. Single threading is very important.
Event loop is a method for js to achieve asynchronousness, and it is also the execution mechanism of js.
There is a big difference between execution and running. JavaScript is executed in different ways in different environments, such as node, browser, Ringo, etc. of. The operation mostly refers to the javascript parsing engine, which is unified.
There are many types of microtasks and macrotasks, such as setImmediate
, etc. The executions are all in common. Interested students can do it themselves learn.
Firmly grasp the two basic points, focus on studying JavaScript seriously, and realize the great dream of becoming a front-end master as soon as possible!
The above is the detailed content of Thoroughly understand the JavaScript execution mechanism. For more information, please follow other related articles on the PHP Chinese website!