Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of execution Mechanism in JavaScript

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the example analysis of the implementation mechanism in JavaScript, which is very detailed and has a certain reference value. Friends who are interested must finish it!

Whether you are a novice or a veteran of javascript, whether you are interviewing for a job or doing daily development work, we often encounter situations where we need to know the output content and order of a given few lines of code. Because javascript is a single-threaded language, we can conclude that:

The javascript is executed in the order in which the statements appear

See here that readers are going to hit people: don't I know that js is executed one line at a time? You don't have to tell me? Take it easy, just because js is executed line by line, we think that js is like this:

Let a = '1console.log (a); let b =' 2console.log (b); copy the code

In fact, however, js goes like this:

SetTimeout (function () {console.log ('timer starts')}); new Promise (function (resolve) {console.log ('execute for loop now'); for (var I = 0; I)

< 10000; i++){ i == 99 && resolve(); }}).then(function(){ console.log('执行then函数啦')});console.log('代码执行结束');复制代码 依照js是按照语句出现的顺序执行这个理念,我自信的写下输出结果: //"定时器开始啦"//"马上执行for循环啦"//"执行then函数啦"//"代码执行结束"复制代码 去chrome上验证下,结果完全不对,瞬间懵了,说好的一行一行执行的呢? 我们真的要彻底弄明白javascript的执行机制了。 1.关于javascript javascript是一门单线程语言,在最新的HTML5中提出了Web-Worker,但javascript是单线程这一核心仍未改变。所以一切javascript版的"多线程"都是用单线程模拟出来的,一切javascript多线程都是纸老虎! 2.javascript事件循环 既然js是单线程,那就像只有一个窗口的银行,客户需要排队一个一个办理业务,同理js任务也要一个一个顺序执行。如果一个任务耗时过长,那么后一个任务也必须等着。那么问题来了,假如我们想浏览新闻,但是新闻包含的超清图片加载很慢,难道我们的网页要一直卡着直到图片完全显示出来?因此聪明的程序员将任务分为两类: 同步任务 异步任务 当我们打开网站时,网页的渲染过程就是一大堆同步任务,比如页面骨架和页面元素的渲染。而像加载图片音乐之类占用资源大耗时久的任务,就是异步任务。关于这部分有严格的文字定义,但本文的目的是用最小的学习成本彻底弄懂执行机制,所以我们用导图来说明: 导图要表达的内容用文字来表述的话: 同步和异步任务分别进入不同的执行"场所",同步的进入主线程,异步的进入Event Table并注册函数。 当指定的事情完成时,Event Table会将这个函数移入Event Queue。 主线程内的任务执行完毕为空,会去Event Queue读取对应的函数,进入主线程执行。 上述过程会不断重复,也就是常说的Event Loop(事件循环)。 我们不禁要问了,那怎么知道主线程执行栈为空啊?js引擎存在monitoring process进程,会持续不断的检查主线程执行栈是否为空,一旦为空,就会去Event Queue那里检查是否有等待被调用的函数。 说了这么多文字,不如直接一段代码更直白: let data = [];$.ajax({ url:www.javascript.com, data:data, success:() =>

{console.log ('sent successfully!);}}) console.log (' end of code execution'); copy code

The above is a simple ajax request code:

Ajax enters Event Table and registers the callback function success.

Execute console.log ('end of code execution').

The ajax event completes, and the callback function success enters Event Queue.

The main thread reads the callback function success from Event Queue and executes it.

I believe that through the above text and code, you have a preliminary understanding of the order in which js is executed. Next, let's study the advanced topic: setTimeout.

3. SetTimeout who loves and hates

There is no need to say more about the famous setTimeout. People's first impression of him is that asynchronous execution can be delayed. We often achieve a delay of 3 seconds:

SetTimeout (() = > {console.log ('delay 3 seconds');}, 3000) copy the code

Gradually, setTimeout uses more places, and problems arise. Sometimes the time delay of writing is 3 seconds, but actually it takes 5 minutes and 6 seconds to execute the function. What's the matter?

Let's first look at an example:

SetTimeout (() = > {task ();}, 3000) console.log ('execute console'); copy the code

According to our previous conclusion, setTimeout is asynchronous and the synchronous task of console.log should be executed first, so our conclusion is:

/ / execute console//task () copy code

Go and verify that the result is correct!

Then let's modify the previous code:

SetTimeout () = > {task ()}, 3000) sleep (10000000) copy the code

At first glance, it looks pretty much the same, but when we execute this code in chrome, we find that it takes far more than 3 seconds for the console to execute task (). The agreed delay of three seconds, why does it take so long now?

At this point, we need to re-understand the definition of setTimeout. Let's start with how the above code is executed:

Task () enters the Event Table and registers, and the timing begins.

Execute the sleep function, very slow, very slow, the timing is still continuing.

3 seconds later, the timing event timeout completes, and task () enters Event Queue, but sleep is too slow to finish, so you have to wait.

The sleep execution is finally finished, and task () finally enters the main thread execution from Event Queue.

After the above process, we know that the setTimeout function adds the task to be executed (task () in this case) to the Event Queue after the specified time, and because the single-threaded task needs to be executed one by one, if the previous task takes too long, then we can only wait, resulting in a real delay time of much more than 3 seconds.

We also often come across code like setTimeout (fn,0). What does it mean to execute in 0 seconds? Can it be carried out immediately?

The answer is no. SetTimeout (fn,0) means to specify the earliest idle time available to the main thread to execute a task, meaning that you don't have to wait any more seconds, as soon as the stack is empty as soon as all the synchronous tasks in the main thread's execution stack are completed. Examples are as follows:

/ / Code 1console.log ('execute here'); setTimeout (() = > {console.log ('execute')}, 0); copy code / / Code 2console.log ('execute here first'); setTimeout (() = > {console.log ('execute')}, 3000); copy code

The output from code 1 is:

/ / execute here / / execute the copy code first

The output from code 2 is:

/ / execute here / /. 3s later// executes the copy code

One thing to add about setTimeout is that even if the main thread is empty, 0 milliseconds is actually unattainable. According to HTML standards, the minimum is 4 milliseconds. Students who are interested can understand for themselves.

4. SetInterval who hates and loves

When it comes to setTimeout, of course you can't miss its twin brother setInterval. They are similar, except that the latter is the execution of the cycle. For execution order, setInterval places registered functions into Event Queue at specified intervals, and if the previous task takes too long, you also need to wait.

The only thing to note is that for setInterval (fn,ms), we already know that fn is not executed every ms second, but that every ms second, fn enters the Event Queue. Once the execution time of setInterval's callback function fn exceeds the delay time ms, there is no time interval at all. Please savor this sentence carefully.

5.Promise and process.nextTick (callback)

We have studied the traditional timer, and then we explore the performance of Promise and process.nextTick (callback).

The definition and function of Promise will not be discussed in this article. Readers who do not understand can learn the Promise of teacher Ruan Yifeng. Process.nextTick (callback), on the other hand, is similar to the node.js version of "setTimeout", calling the callback callback function in the next loop of the event loop.

Let's get down to business. In addition to synchronous and asynchronous tasks in a broad sense, we have a more nuanced definition of tasks:

Macro-task (Macro Task): including the overall code script,setTimeout,setInterval

Micro-task (micro task): Promise,process.nextTick

Different types of tasks will enter the corresponding Event Queue, such as setTimeout and setInterval will enter the same Event Queue.

The order of the event loop, which determines the order in which the js code is executed. After entering the overall code (macro task), start the first loop. Then perform all the micro tasks. Then start with the macro task again, find one of the task queues to finish execution, and then execute all the micro tasks. It sounds a little roundabout, but let's use the code at the beginning of the article to illustrate:

SetTimeout (function () {console.log ('setTimeout');}) new Promise (function (resolve) {console.log (' promise');}) .then (function () {console.log ('then');}) console.log (' console'); copy the code

This code enters the main thread as a macro task.

If you encounter setTimeout first, register its callback function and distribute it to the macro task Event Queue. (the registration process is the same as above, which is not described below)

Next, Promise,new Promise executes immediately, and the then function is distributed to the micro task Event Queue.

If you encounter console.log (), execute it immediately.

All right, the overall code script ends as the first macro task, so what are the micro tasks? We found that then is in the microtask Event Queue, executing.

Ok, the first round of the event loop is over, and we start the second round, of course, starting with the macro task Event Queue. We found the callback function corresponding to setTimeout in the macro task Event Queue and executed it immediately.

End.

The relationship between event loops, macro tasks, and micro tasks is shown in the figure:

Let's analyze a more complex piece of code to see if you have really mastered the execution mechanism of 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')}) copy the code

The analysis of the first round of event cycle process is as follows:

The overall script enters the main thread as the first macro task, encounters console.log, and outputs 1.

When setTimeout is encountered, its callback function is distributed to the macro task Event Queue. Let's call it setTimeout1 for the time being.

When process.nextTick () is encountered, its callback function is distributed to the microtask Event Queue. We write it down as process1.

If you encounter Promise,new Promise, you will execute it directly and output 7. Then is distributed to the microtask Event Queue. We write it down as then1.

SetTimeout is also encountered, and its callback function is distributed to the macro task Event Queue, which we call setTimeout2.

| | Macro task Event Queue | Micro task Event Queue | |

The above table shows the Event Queue at the end of the first round of event loop macro task, by which time 1 and 7 have been output.

We found two micro tasks, process1 and then1.

Execute process1 and output 6.

Execute then1 and output 8.

All right, the first round of events is officially over, and the result of this round is the output of 1, 7, 6, 8. So the second round of the time loop starts with the setTimeout1 macro task:

First output 2. Next you encounter process.nextTick (), which is also distributed to the microtask Event Queue, marked process2. New Promise immediately executes the output 4 and then distributes it to the micro-task Event Queue, which is marked then2.

Macro task Event Queue micro task Event QueuesetTimeout2process2

Then2

When the second round of the event loop macro task ends, we find that there are two micro tasks, process2 and then2, that can be executed.

Output 3.

Output 5.

The second round of the event cycle is over, and the second round output is 2, 4, 4, 3, 5.

The third round of the event loop begins, and there is only setTimeout2 left to execute.

Direct output 9.

Distribute process.nextTick () to the microtask Event Queue. Record it as process3.

Execute new Promise directly and output 11.

Distribute the then to the microtask Event Queue and mark it as then3.

Macro task Event Queue micro task Event Queue

Process3

Then3

The third round of event loop macro task execution ends, executing two micro tasks, process3 and then3.

Output 10.

Output 12.

The third round of the event cycle ends, and the third round outputs 9 minutes 11, 10, 10, 12.

The whole code, a total of three event loops, the complete output is 1, 7, 6, 8, 2, 4, 3, 5, 9, 11, 10, 12.

(please note that the event monitoring dependency libuv in the node environment is not exactly the same as the front-end environment, and the output order may be incorrect.)

6. Async written at the end of (1) js

We said from the very beginning that javascript is a single-threaded language. No matter what the new framework and new syntax sugar implements the so-called asynchronism, it is actually simulated by synchronous methods. It is very important to firmly grasp single-threading.

(2) event cycle Event Loop

Event loop is a way for js to implement asynchronism, and it is also the execution mechanism of js.

(3) execution and operation of javascript

There is a big difference between execution and running. Javascript is executed differently in different environments, such as node, browser, Ringo, and so on. And running mostly refers to the javascript parsing engine, which is unified.

(4) setImmediate

There are many kinds of micro tasks and macro tasks, such as setImmediate, etc., the execution has something in common, interested students can understand for themselves.

(5) Last

Javascript is a single threaded language

Event Loop is the execution mechanism of javascript.

The above is all the content of the article "sample Analysis of execution Mechanism in JavaScript". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report