Table of Contents
1. Experiment
2. Event Loop
3. Job Queue and Task Queue
Summary
Home Web Front-end JS Tutorial An in-depth analysis of why Promise is faster than setTimeout()

An in-depth analysis of why Promise is faster than setTimeout()

Feb 04, 2021 pm 04:04 PM
javascript promise

Why is Promise faster than setTimeout()? The following article will analyze the reasons for you. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

An in-depth analysis of why Promise is faster than setTimeout()

Related recommendations: "javascript video tutorial"

1. Experiment

Let's do an experiment. Which executes faster: an immediately resolved Promise or an immediate setTimeout (that is, a setTimeout of 0 milliseconds)?

Promise.resolve(1).then(function resolve() {
  console.log('Resolved!');
});

setTimeout(function timeout() {
  console.log('Timed out!');
}, 0);

// 'Resolved!'
// 'Timed out!'
Copy after login

promise.resolve(1) is a static Function that returns an promise that resolves immediately. setTimeout(callback, 0)Execute the callback function with a delay of 0 milliseconds.

We can see that 'Resolved!' is printed first, and then Timeout completed! is printed. The promise that is resolved immediately is faster than the immediate setTimeout .

is because Promise.resolve(true).then(...) was called before setTimeout(..., 0), so the Promise process Will it be faster? Fair question.

So, let’s change the experimental conditions slightly, and then call setTimeout(..., 0):

setTimeout(function timeout() {
  console.log('Timed out!');
}, 0);

Promise.resolve(1).then(function resolve() {
  console.log('Resolved!');
});

// 'Resolved!'
// 'Timed out!'
Copy after login

setTimeout(..., 0 ) is called before Promise.resolve(true).then(...). However, Resolved! is printed first and then 'Timed out!'.

Why is this?

2. Event Loop

Questions related to asynchronous JS can be answered by studying the event loop. Let’s review the main components of how asynchronous JS works.

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-Lt9zVHTf-1611275604640)(/img/bVcMQaI)]

Call stack is a LIFO (last in first out) structure that stores the execution context created during code execution. Simply put, the call stack executes these functions.

Web api is where asynchronous operations (fetch requests, promises, timers) and their callbacks wait for completion.

**task queue (task queue) is a FIFO (first in, first out)** structure, which saves the callbacks of asynchronous operations that are ready to be executed. For example, the callback function of setTimeout() that times out or the click button event handler that is ready to be executed are queued in the task queue.

**job queue (job queue)** is a FIFO (first in, first out) structure, which saves the callbacks of promise that are ready to be executed. For example, a completed promise's resolve or reject callback is enqueued in the job queue.

Finally, the event loop permanently monitors whether the call stack is empty. If the call stack is empty, the event loop looks at the job queue or task queue and dispatches any callbacks that are ready to be executed onto the call stack.

3. Job Queue and Task Queue

Let’s look at this experiment from the perspective of the event loop, and I will analyze the code execution step by step.

A) The call stack executes setTimeout(..., 0) and schedules a timer, timeout()The callback is stored in the Web API:

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-SLk0AUa5-1611275604642)(/img/bVcMQdg)]

[External link image The transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-Zr7usYTK-1611275604643)(/img/bVcMQc9)]

B) Call stack execution Promise.resolve (true).then(resolve)And arrange a promise solution. resolved()The callback is stored in the Web API:

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-JTwSnLYS- 1611275604646)(/img/bVcMQdh)]

[The external link image transfer failed. The source site may have an anti-hotlink mechanism. It is recommended to save the image and upload it directly (img-k5cRhqzN-1611275604648)(/img/bVcMQdi )]

C) The promise is resolved immediately and the timer is executed immediately. In this way, the timer callback timeout() enters the task queue, and the promise callback resolve() enters the job queue

[External link picture transfer Failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-iMfLB2YJ-1611275604649)(/img/bVcMQdS)]

D) Now comes the interesting part: job queue (microtask) ) has a higher priority than the task queue (macro task). The event loop takes the promise callback resolve() from the job queue and puts it into the call stack. Then, the call stack executes the promise callback resolve():

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-nnqfgoo1 -1611275604650)(/img/bVcMQey)]

E) Finally, the event loop dequeues the timer callback timeout() from the task queue onto the call stack. Then, the call stack executes the timer callback timeout():

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img- Fj54WaI0-1611275604650)(/img/bVcMQeB)]

The call stack is empty and the execution of the script has been completed.

Summary

Why do immediately resolved promises process faster than immediate execution timers?

Due to the existence of event loop priorities, compared to the task queue (which stores the timeout's setTimeout() callback), the job queue (which stores the implemented PromiseCallback) has higher priority.

Original address: https://dmitripavlutin.com/javascript-promises-settimeout/

Author: Milos Protic

Translation address: https://segmentfault .com/a/1190000038769853

For more computer programming related knowledge, please visit: Programming Video! !

The above is the detailed content of An in-depth analysis of why Promise is faster than setTimeout(). 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
1252
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Keeping your word: The pros and cons of delivering on your promises Keeping your word: The pros and cons of delivering on your promises Feb 18, 2024 pm 08:06 PM

In daily life, we often encounter problems between promises and fulfillment. Whether in a personal relationship or a business transaction, delivering on promises is key to building trust. However, the pros and cons of commitment are often controversial. This article will explore the pros and cons of commitments and give some advice on how to keep your word. The promised benefits are obvious. First, commitment builds trust. When a person keeps his word, he makes others believe that he is a trustworthy person. Trust is the bond established between people, which can make people more

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

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

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

See all articles