Home Web Front-end JS Tutorial js event loop mechanism example analysis

js event loop mechanism example analysis

Dec 14, 2017 am 09:21 AM
javascript analyze Example

This article mainly introduces the js event loop mechanism, and analyzes js usage and techniques through examples. Let's learn and share together. I hope everyone can use the js event loop mechanism.


var start = new Date()
setTimeout(function () {
 var end = new Date
 console.log('Time elapsed:', end - start, 'ms')
}, 500)
while (new Date() - start < 1000) {
}
Copy after login


Are there any other languages ​​that can accomplish the desired function? Java, in Java.util.Timer, the solution to scheduled tasks is implemented through multi-threading. The task object is stored in the task queue, and a dedicated scheduling thread completes the execution of the task in a new sub-thread

js is single-threaded

The main purpose of JavaScript 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.

In order to take advantage of the computing power of multi-core CPUs, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, but the child threads are completely controlled by the main thread and are not allowed to operate the DOM. Therefore, this new standard does not change the single-threaded nature of JavaScript.

Function call stack and task queue

Call stack

A call will be formed when JS is executed Stack. When a function is called, the return address, parameters, and local variables will be pushed onto the stack. If another function is called in the currently running function, the relevant content of the function will also be pushed onto the top of the stack. The function is executed. , the call stack will be popped. The variables will also be popped. Since complex type values ​​are stored in the heap, only pointers are popped. Their values ​​are still in the heap and are recycled by the GC.

Event Loop (event loop) & task queue (task queue)

JavaScript main thread has an execution stack and a task queue

When encountering an asynchronous operation (for example: setTimeout, AJAX), Asynchronous operations will be executed by the browser (OS). After these tasks are completed, the browser will push the predefined callback function into the task queue of the main thread. When the execution stack of the main thread is cleared, the task will be read. The callback function in the queue, when the task queue is read, the main thread continues to execute, thus entering an infinite loop, which is the event loop.

The main thread execution stack & task queue loop execution constitutes an event Loop

Conclusion

setTimeout() just inserts the event into the "task queue". It must wait until the current code (execution stack) is completed before the main thread Will execute the callback function it specifies. If the current code takes a long time, it may take a long time, so there is no way to guarantee that the callback function will be executed at the time specified by setTimeout().

Another example


(function test() {
 setTimeout(function() {console.log(4)}, 0);
 new Promise(function executor(resolve) {
 console.log(1);
 for( var i=0 ; i<10000 ; i++ ) {
 i == 9999 && resolve();
 }
 console.log(2);
 }).then(function() {
 console.log(5);
 });
 console.log(3);
})()
Copy after login


##Macrotask & Microtask

Macrotask and microtask are two categories of asynchronous tasks. When suspending tasks, the JS engine will divide all tasks into these two queues according to categories. First, the first task will be taken out of the macrotask queue (this queue is also called the task queue). After execution, it will be taken out of the microtask queue. All tasks are executed sequentially; then the macrotask task is fetched, and the cycle starts again until all tasks from both queues are fetched.

macro-task: script (overall code), setTimeout, setInterval, setImmediate, I/O, UI rendering

micro-task: process.nextTick, Promises (here refers to the native Promise implemented by the browser) , Object.observe, MutationObserver

Conclusion

All code (script) macrotask -> microtask queue (contains promise.then) -> macrotask(setTimeout) -> Next microtask

Node.js event loop


process.nextTick & setImmediate


process.nextTickThe specified task always occurs before all asynchronous tasks


setImmediateThe specified task is always executed in the next Event Loop


process.nextTick(function A() {
 console.log(1);
 process.nextTick(function B(){console.log(2);});
});
setTimeout(function timeout() {
 console.log(&#39;TIMEOUT FIRED&#39;);
}, 0)
Copy after login


new Promise(function(resolve) {
 console.log(&#39;glob1_promise&#39;);
 resolve();
}).then(function() {
 console.log(&#39;glob1_then&#39;)
})
process.nextTick(function() {
 console.log(&#39;glob1_nextTick&#39;);
})
Copy after login
Related recommendations:

Front-end Advanced (Twelve): Detailed explanation of the event loop mechanism

##js Specific method to change div color in a loop_javascript skills

Node.js event loop tutorial

The above is the detailed content of js event loop mechanism 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 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)

Oracle DECODE function detailed explanation and usage examples Oracle DECODE function detailed explanation and usage examples Mar 08, 2024 pm 03:51 PM

The DECODE function in Oracle is a conditional expression that is often used to return different results based on different conditions in query statements. This article will introduce the syntax, usage and sample code of the DECODE function in detail. 1. DECODE function syntax DECODE(expr,search1,result1[,search2,result2,...,default]) expr: the expression or field to be compared. search1,

Go language indentation specifications and examples Go language indentation specifications and examples Mar 22, 2024 pm 09:33 PM

Indentation specifications and examples of Go language Go language is a programming language developed by Google. It is known for its concise and clear syntax, in which indentation specifications play a crucial role in the readability and beauty of the code. effect. This article will introduce the indentation specifications of the Go language and explain in detail through specific code examples. Indentation specifications In the Go language, tabs are used for indentation instead of spaces. Each level of indentation is one tab, usually set to a width of 4 spaces. Such specifications unify the coding style and enable teams to work together to compile

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Analysis of the reasons why the secondary directory of DreamWeaver CMS cannot be opened Mar 13, 2024 pm 06:24 PM

Title: Analysis of the reasons and solutions for why the secondary directory of DreamWeaver CMS cannot be opened. Dreamweaver CMS (DedeCMS) is a powerful open source content management system that is widely used in the construction of various websites. However, sometimes during the process of building a website, you may encounter a situation where the secondary directory cannot be opened, which brings trouble to the normal operation of the website. In this article, we will analyze the possible reasons why the secondary directory cannot be opened and provide specific code examples to solve this problem. 1. Possible cause analysis: Pseudo-static rule configuration problem: during use

Application and example analysis of PHP dot operator Application and example analysis of PHP dot operator Mar 28, 2024 pm 12:06 PM

Application and example analysis of PHP dot operator In PHP, the dot operator (".") is an operator used to connect two strings. It is very commonly used and very flexible when concatenating strings. By using the dot operator, we can easily concatenate multiple strings to form a new string. The following will introduce the use of PHP dot operators through example analysis. 1. Basic usage First, let’s look at a basic usage example. Suppose there are two variables $str1 and $str2, which store two words respectively.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Analyze whether Tencent's main programming language is Go Analyze whether Tencent's main programming language is Go Mar 27, 2024 pm 04:21 PM

Title: Is Tencent’s main programming language Go: An in-depth analysis. As China’s leading technology company, Tencent has always attracted much attention in its choice of programming languages. In recent years, some people believe that Tencent mainly adopts Go as its main programming language. This article will conduct an in-depth analysis of whether Tencent's main programming language is Go, and give specific code examples to support this view. 1. Application of Go language in Tencent Go is an open source programming language developed by Google. Its efficiency, concurrency and simplicity are loved by many developers.

Example of Curl Get command Example of Curl Get command Mar 20, 2024 pm 06:56 PM

In Linux, URL or Curl client is a popular command line utility that allows you to transfer data over the network using various protocols such as HTTPS, HTTP, FTP, etc. It allows you to send and receive data using its get, post and request methods. Among them, you need to use the &quot;get&quot; method frequently. Therefore, it becomes crucial to learn various methods and various options that you can use to increase your productivity. &quot;Performing a curl operation is as simple as entering a few simple commands. Although it seems simple, many users do not fully realize its potential. Therefore, this short guide provides some information on how to perform curl operations on Linux systems. Example using the &quot;curlget&quot; command.&quot; Curl

See all articles