js event loop mechanism example analysis
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) { }
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); })()
##Macrotask & Microtask
micro-task: process.nextTick, Promises (here refers to the native Promise implemented by the browser) , Object.observe, MutationObserver
Conclusion
process.nextTick(function A() { console.log(1); process.nextTick(function B(){console.log(2);}); }); setTimeout(function timeout() { console.log('TIMEOUT FIRED'); }, 0)
new Promise(function(resolve) { console.log('glob1_promise'); resolve(); }).then(function() { console.log('glob1_then') }) process.nextTick(function() { console.log('glob1_nextTick'); })
Front-end Advanced (Twelve): Detailed explanation of the event loop mechanism
##js Specific method to change div color in a loop_javascript skillsNode.js event loop tutorialThe 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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,

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

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

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 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.

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

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.

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 "get" method frequently. Therefore, it becomes crucial to learn various methods and various options that you can use to increase your productivity. "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 "curlget" command." Curl
