search
HomeWeb Front-endJS TutorialAn in-depth analysis of why Promise is faster than setTimeout()

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!'

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!'

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
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

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

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 Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version