search
HomeWeb Front-endJS TutorialForced sorting of javascript event loop

Forced sorting of javascript event loop

Jul 19, 2017 pm 03:42 PM
javascriptjs

js single thread

js is single-threaded, which is more conducive to user interaction and DOM operations; for a detailed explanation of processes and threads, you can click on the portal; although webworker can implement multi-threading, in essence It is also single-threaded. The threads created by webworker are controlled by the main thread and can only perform calculations;

js synchronization and asynchronous

Synchronous execution: that is, the js main thread executes tasks in sequence , if you operate webAPI/ajax and other codes, you will wait for its response and the subsequent code will not be executed, that is, the next task must wait until the previous task is completed;

Asynchronous execution: js is single-threaded and does not It has asynchronous capabilities, but the browser can; when js is executed and encounters webAPI (such as setTimeout/ajax, etc.), a value will be returned immediately, thereby not blocking the main thread, and the real asynchronous is executed by the browser, and it will be discussed after it is completed. The callback function is pushed into the message queue of the js main thread and waits for the main thread to call;

Event loop mechanism [Event-loop]

When js is executed, its main thread has an execution stack [personal habit is called Call stack] (stack) and a message queue [also called task queue or event queue] (Event-queue); when js encounters a function during execution, it will be pushed onto the stack and popped out of the stack after the function is executed, and the main thread calls Execute the stack and execute it. If it encounters webAPI, it will be executed asynchronously; when there is no task in the execution stack, the main thread will query the message queue. If the query is successful, the queried task will be pushed into the stack for execution until the execution stack is empty, and the message will be queried again. Queuing up to form a loop is the famous event loop [Event-loop]; since asynchronous execution is completed by the browser, it is easy to understand why operating dom events when the js thread is blocked will be executed sequentially after the thread is restored, [js main thread The task queue is pushed by the browser, and the js thread is blocked! == The browser thread is blocked. In other words, even if the main thread is blocked, it will not prevent the task from being pushed into the task queue]; draw a sketch;

Here is another piece of code:

      // 主线程执行fn1任务  1function fn1(){ 
                console.log("任务1执行")// 遇到webAPI立即返回 这里是undefined值 并交给浏览器对应线程处理 2  // 浏览器收到后 0 毫秒将回调函数推入消息列队; 异步执行setTimeout(function(){// 查询到一个回调任务 入栈执行    5console.log("回调1执行")// 遇到webAPI立即返回 这里是undefined值 并交给浏览器对应线程处理  6  // 浏览器收到后 500   毫秒将回调函数推入消息列队; 异步执行setTimeout(function(){// 查询到一个回调任务 入栈执行    7console.log("回调2执行")
                    },500)
                },0)
            }// 主线程执行fn2任务 3function fn2(){console.log("任务2执行")}// 执行栈没有可执行任务 开始查询消息列队 4

Macrotasks and Microtasks

The message queue is divided into two types, namely Macrotasks[Task Queue] and Microtasks[Microtasks Queue] ];

  • macrotasks: setTimeout, setInterval, setImmediate, I/O, UI rendering

  • microtasks: process.nextTick, Promises, Object.MutationObserver

This raises a question, which of the two should execute first? The Promise/A+ specification states:

Here “platform code” means engine, environment, and promise implementation code. In practice, this requirement ensures that onFulfilled and onRejected execute asynchronously, after the event loop turn in which then is called, and with a fresh stack. This can be implemented with either a “macro-task” mechanism such as setTimeout or setImmediate, or with a “micro-task” mechanism such as MutationObserver or process.nextTick. Since the promise implementation is considered platform code, it may itself contain a task-scheduling queue or “trampoline” in which the handlers are called.
In fact, the execution process is also easy to understand It is also a circular query. Based on the previous query, when querying the message queue, microtasks will be queried first. After all tasks are executed, macrotasks will be queried. If there are microtasks tasks in macrotasks, the next step will be The query will still be executed first microtasks queue task and then query macrotasks. This is repeated until the message queue [two Queue] has no tasks;
ok our previous code [the promise feature is es6, so the node environment is used]
console.log(170 Promise(89100 Promise(34562);
// 1 2 3 4 5 6 7 8 9 10

The above code execution process:

js executes console 1. When setTimeout is encountered, it is changed to asynchronous execution, and when setTimeout is encountered again, it is executed asynchronously again. Then the execution encounters a promise and is pushed into the microtasks type task queue for execution. Console 2 At this point, the execution stack is empty and the message queue is started to be queried. First, query microtasks and find that there is a task that can be executed. Then the task will be pushed into the stack for execution and the corresponding print will be 3 4 5 6 [As long as is found If microtasks is not empty, it will be executed until it is empty】; Query the message queue again. At this time, the microtasks queue has no tasks to execute. Then query the macrotasks queue and find a setTimeout callback waiting to be executed. Then Push the stack and pop it out, printing 7; query the queue again. At this time, the microtasks queue still has no tasks. Then query the macrotasks queue and find a setTimeou callback waiting to be executed. When the stack is executed, it is found that the promise is pushed into microtasks. The queue is popped out of the stack, and the execution stack is empty again. Query the message queue and find that microtasks have tasks that can be executed, push them into the stack and pop them out; print the response 8 9 10; at this point the execution ends and the main thread is in a waiting state;

##

The above is the detailed content of Forced sorting of javascript event loop. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools