Home  >  Article  >  Web Front-end  >  Thoroughly understand the JavaScript execution mechanism

Thoroughly understand the JavaScript execution mechanism

coldplay.xixi
coldplay.xixiforward
2020-06-16 16:47:491638browse

Thoroughly understand the JavaScript execution mechanism

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:

  • javascript is executed in the order in which statements appear

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(&#39;执行then函数啦&#39;)
});console.log(&#39;代码执行结束&#39;);复制代码

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.

1. About 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!

2.javascript event loop

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:

  • Synchronous tasks
  • Asynchronous tasks

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:

  • Synchronous and asynchronous tasks enter different execution "places" respectively, synchronously enter the main thread, asynchronously enter the Event Table and Register function.
  • When the specified thing is completed, the Event Table will move this function into the Event Queue.
  • The task in the main thread is empty after execution. It will go to the Event Queue to read the corresponding function and enter the main thread for execution.
  • The above process will be repeated continuously, which is often called Event Loop.

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:

  • ajax enters the Event Table and registers the callback function success.
  • Executionconsole.log('Code execution ends').
  • ajax event is completed, the callback function success enters the Event Queue.
  • The main thread reads the callback function 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.

3. The love-hate 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函数,很慢,非常慢,计时仍在继续。
  • 3秒到了,计时事件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毫秒。有兴趣的同学可以自行了解。

4.又恨又爱的setInterval

上面说完了setTimeout,当然不能错过它的孪生兄弟setInterval。他俩差不多,只不过后者是循环的执行。对于执行顺序来说,setInterval会每隔指定的时间将注册的函数置入Event Queue,如果前面的任务耗时太久,那么同样需要等待。

唯一需要注意的一点是,对于setInterval(fn,ms)来说,我们已经知道不是每过ms秒会执行一次fn,而是每过ms秒,会有fn进入Event Queue。一旦setInterval的回调函数fn执行时间超过了延迟时间ms,那么就完全看不出来有时间间隔了。这句话请读者仔细品味。

5.Promise与process.nextTick(callback)

传统的定时器我们已经研究过了,接着我们探究Promiseprocess.nextTick(callback)的表现。

Promise的定义和功能本文不再赘述,不了解的读者可以学习一下阮一峰老师的Promise。而process.nextTick(callback)类似node.js版的"setTimeout",在事件循环的下一次循环中调用 callback 回调函数。

我们进入正题,除了广义的同步任务和异步任务,我们对任务有更精细的定义:

  • macro-task(宏任务):包括整体代码script,setTimeout,setInterval
  • micro-task(微任务):Promise,process.nextTick

不同类型的任务会进入对应的Event Queue,比如setTimeoutsetInterval会进入相同的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。(注册过程与上同,下文不再描述)
  • 接下来遇到了Promisenew Promise立即执行,then函数分发到微任务Event Queue。
  • 遇到console.log(),立即执行。
  • 好啦,整体代码script作为第一个宏任务执行结束,看看有哪些微任务?我们发现了then在微任务Event Queue里面,执行。
  • ok,第一轮事件循环结束了,我们开始第二轮循环,当然要从宏任务Event Queue开始。我们发现了宏任务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')
    })
})复制代码

第一轮事件循环流程分析如下:

  • 整体script作为第一个宏任务进入主线程,遇到console.log,输出1。
  • 遇到setTimeout,其回调函数被分发到宏任务Event Queue中。我们暂且记为setTimeout1
  • 遇到process.nextTick(),其回调函数被分发到微任务Event Queue中。我们记为process1
  • 遇到Promisenew Promise直接执行,输出7。then被分发到微任务Event Queue中。我们记为then1
  • 又遇到了setTimeout,其回调函数被分发到宏任务Event Queue中,我们记为setTimeout2
宏任务Event Queue 微任务Event Queue
setTimeout1 process1
setTimeout2 then1
  • 上表是第一轮事件循环宏任务结束时各Event Queue的情况,此时已经输出了1和7。

  • 我们发现了process1then1两个微任务。

  • 执行process1,输出6。
  • 执行then1,输出8。

好了,第一轮事件循环正式结束,这一轮的结果是输出1,7,6,8。那么第二轮时间循环从setTimeout1宏任务开始:

  • 首先输出2。接下来遇到了process.nextTick(),同样将其分发到微任务Event Queue中,记为process2new Promise立即执行输出4,then也分发到微任务Event Queue中,记为then2
宏任务Event Queue 微任务Event Queue
setTimeout2 process2

then2
  • 第二轮事件循环宏任务结束,我们发现有process2then2两个微任务可以执行。
  • 输出3。
  • 输出5。
  • 第二轮事件循环结束,第二轮输出2,4,3,5。
  • 第三轮事件循环开始,此时只剩setTimeout2了,执行。
  • 直接输出9。
  • process.nextTick()分发到微任务Event Queue中。记为process3
  • 直接执行new Promise,输出11。
  • then分发到微任务Event Queue中,记为then3
宏任务Event Queue 微任务Event Queue

process3

then3
  • The third round of event loop macro task execution ends, and two micro tasks process3 and then3 are executed.
  • Output 10.
  • Output 12.
  • The third round of event loop ends, and the third round outputs 9, 11, 10, 12.

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)

6. Write at the end

(1)js Asynchronous

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.

(2) Event Loop Event Loop

Event loop is a method for js to achieve asynchronousness, and it is also the execution mechanism of js.

(3)Javascript execution and running

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.

(4)setImmediate

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.

(5) The last thing

  • javascript is a single-threaded language
  • Event Loop is the execution mechanism of javascript

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!

Recommended tutorial: "JavaScript Basics Tutorial"

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!

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