Home >Web Front-end >JS Tutorial >Detailed analysis of the operating mechanism in js (example analysis)

Detailed analysis of the operating mechanism in js (example analysis)

不言
不言forward
2018-10-29 14:04:471836browse

This article brings you a detailed analysis of the operating mechanism in js (example analysis). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Introduction

This article introduces the JavaScript operating mechanism. This part is relatively abstract. Let’s start with an interview question:

console.log(1);
setTimeout(function(){
console.log(3);
},0);
console.log(2);
请问数字打印顺序是什么?

It seems very simple, but if you don’t understand the running mechanism of JavaScript, it is easy to get the wrong answer. The answer to the question is to output 1 2 3 in sequence. If you have any doubts, there is a detailed explanation below.

2. Understand the concept of single-threading in JS

One of the major features of JavaScript language is single-threading, that is to say, Only one thing can be done at the same time . So why can't JavaScript have multiple threads? This can improve efficiency.
The single thread of JavaScript is related to its purpose. As a browser scripting language, JavaScript's main purpose is to interact with users and manipulate the DOM. This determines that it can only be single-threaded, otherwise it will cause very complex synchronization problems. For example, suppose JavaScript has two threads at the same time. One thread adds content to a certain DOM node, and the other thread deletes the node. In this case, which thread should the browser use?
So, in order to avoid complexity, JavaScript has been single-threaded since its birth. This has become the core feature of this language and will not change in the future.

3. Understanding task queue (message queue)

Single thread means that all tasks need to be queued, and the next task will not be executed until the previous task is completed. If the previous task takes a long time, the next task will have to wait. The designers of the JavaScript language realized this problem and divided all tasks into two types, One is synchronous task (synchronous), and the other is asynchronous task (asynchronous). Synchronous tasks refer to tasks queued for execution on the main thread. The next task can only be executed after the previous task is executed; asynchronous tasks refer to tasks that do not enter the main thread but enter the "task queue". Task, only when the "task queue" notifies the main thread that an asynchronous task can be executed, will the task enter the main thread for execution. Next, we use two examples to illustrate the difference between synchronous tasks and asynchronous tasks:

console.log("A");
while(true){ }
console.log("B");
请问最后的输出结果是什么?

If your answer is A, congratulations on the correct answer, because this is a synchronous task, and the program is executed from top to bottom. While() loops endlessly, the following statements cannot be executed.

console.log("A");
setTimeout(function(){
console.log("B");
},0);
while(true){}
请问最后的输出结果是什么?

If your answer is A, congratulations, you now have a superficial understanding of the js operating mechanism! The setTimeout() in the question is an asynchronous task. No asynchronous tasks will be executed until all synchronous tasks are executed. This will be explained in detail below.

4. Understand Event Loop

The running mechanism of asynchronous execution is as follows:

  1. All synchronous tasks are on the main thread Execution, forming an execution context stack.

  2. Besides the main thread, there is also a "task queue". As long as the asynchronous task has running results, an event is placed in the "task queue".

  3. Once all synchronization tasks in the "execution stack" have been executed, the system will read the "task queue" to see what events are in it. Those corresponding asynchronous tasks end the waiting state, enter the execution stack, and start execution.

  4. The main thread keeps repeating the third step above.

The main thread reads events from the "task queue". This process is cyclic, so the entire operating mechanism is also called Event Loop. . As long as the main thread is empty, it will read the "task queue". This is the running mechanism of JavaScript. This process will cycle over and over again. The picture below illustrates this point well.

Detailed analysis of the operating mechanism in js (example analysis)

5. Which statements will be put into the asynchronous task queue and the timing

Generally speaking, there are the following four types of statements Put into the asynchronous task queue:

  1. setTimeout and setlnterval

  2. DOM event

  3. in ES6 Promise

  4. Ajax asynchronous request

javascript code runs in two stages:

1. Pre-parsing---advance all function definitions, all variable declarations in advance, and do not assign variables in advance

2. Execution---execute from top to bottom ( According to the js operating mechanism)

As for the timing of putting it into the asynchronous task queue, we will explain it in detail through the setTimeout example and the Ajax example:

例题1
for (var i = 0; i <p>for循环一次碰到一个 setTimeout(),<strong>并不是马上把setTimeout()拿到异步队列中,而要等到一秒后,才将其放到任务队列里面</strong>,一旦"执行栈"中的所有同步任务执行完毕(即for循环结束,此时i已经为5),系统就会读取已经存放"任务队列"的setTimeout()(有五个),于是答案是输出5个5。</p><p>上面也提到,<strong>在到达指定时间时,定时器就会将相应回调函数插入“任务队列”尾部。这就是“定时器(timer)”功能</strong>。</p><p><strong>关于定时器的重要补充</strong>:</p><p>定时器包括setTimeout与 setInterval 两个方法。它们的第二个参数是指定其回调函数推迟/每隔多少毫秒数后执行。</p><p>对于第二个参数有以下需要注意的地方:</p><p>当第二个参数缺省时,默认为 0;</p><p>当指定的值小于 4 毫秒,则增加到 4ms(4ms 是 HTML5 标准指定的,对于 2010 年及之前的浏览器则是 10ms);也就是说至少需要4毫秒,该setTimeout()拿到任务队列中。</p><pre class="brush:php;toolbar:false">例题2
$.ajax({
url:“xxxxx",
success:function (result){
console.log("a")
   }
})
setTimeout(function (){
console.log("b")
},100)
setTimeout(function (){
console.log("c")
})
console.log("d");

Detailed analysis of the operating mechanism in js (example analysis)

ajax加载完成时才会放入异步队列,至于这段时间不确定,所有有两种情况:①大于100ms,最后的结果是 d c b a ;②小于100ms,最后的结果便是d c a b。

六、题外话

如果要输出0~4,上面例题应该如何修改?

  1. 将var变为let

for (let i = 0; i <p>2.加个立即执行函数</p><pre class="brush:php;toolbar:false">for (var i = 0; i <p>3.也可以通过这样加闭包</p><pre class="brush:php;toolbar:false">for(var i = 1;i 

The above is the detailed content of Detailed analysis of the operating mechanism in js (example analysis). For more information, please follow other related articles on the PHP Chinese website!

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