Table of Contents
2. Understand the concept of single-threading in JS
3. Understanding task queue (message queue)
4. Understand Event Loop
5. Which statements will be put into the asynchronous task queue and the timing
六、题外话
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)

Oct 29, 2018 pm 02:04 PM
css html html5 javascript node.js

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);
请问数字打印顺序是什么?
Copy after login

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");
请问最后的输出结果是什么?
Copy after login

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){}
请问最后的输出结果是什么?
Copy after login

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");
Copy after login

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 
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
What Does H5 Refer To? Exploring the Context What Does H5 Refer To? Exploring the Context Apr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

HTML: The Structure, CSS: The Style, JavaScript: The Behavior HTML: The Structure, CSS: The Style, JavaScript: The Behavior Apr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web Design The Future of HTML: Evolution and Trends in Web Design Apr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

HTML: Building the Structure of Web Pages HTML: Building the Structure of Web Pages Apr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

Is H5 a Shorthand for HTML5? Exploring the Details Is H5 a Shorthand for HTML5? Exploring the Details Apr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web Development H5 and HTML5: Commonly Used Terms in Web Development Apr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

How to optimize website performance: Experiences and lessons learned from using the Minify library How to optimize website performance: Experiences and lessons learned from using the Minify library Apr 17, 2025 pm 11:18 PM

In the process of developing a website, improving page loading has always been one of my top priorities. Once, I tried using the Miniify library to compress and merge CSS and JavaScript files in order to improve the performance of the website. However, I encountered many problems and challenges during use, which eventually made me realize that Miniify may no longer be the best choice. Below I will share my experience and how to install and use Minify through Composer.

See all articles