惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threatpost
博客园 - 叶小钗
T
The Blog of Author Tim Ferriss
Recent Announcements
Recent Announcements
D
DataBreaches.Net
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
Netflix TechBlog - Medium
Microsoft Azure Blog
Microsoft Azure Blog
Microsoft Security Blog
Microsoft Security Blog
B
Blog
U
Unit 42
有赞技术团队
有赞技术团队
博客园 - 聂微东
GbyAI
GbyAI
宝玉的分享
宝玉的分享
F
Full Disclosure
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
MyScale Blog
MyScale Blog
Jina AI
Jina AI
Martin Fowler
Martin Fowler
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Docker
P
Proofpoint News Feed
A
About on SuperTechFans
I
InfoQ
博客园 - 【当耐特】
C
Check Point Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy & Cybersecurity Law Blog
T
Threat Research - Cisco Blogs
Y
Y Combinator Blog
Project Zero
Project Zero
WordPress大学
WordPress大学
小众软件
小众软件
AWS News Blog
AWS News Blog
博客园 - 司徒正美
T
The Exploit Database - CXSecurity.com
L
LINUX DO - 热门话题
I
Intezer
Engineering at Meta
Engineering at Meta
C
CXSECURITY Database RSS Feed - CXSecurity.com
J
Java Code Geeks
T
Tenable Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Last Week in AI
Last Week in AI
C
CERT Recently Published Vulnerability Notes

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Why Promises Are Faster Than setTimeout()?
Dmitri Pavlutin · 2020-12-29 · via Dmitri Pavlutin Blog

1. The experiment

Let's try an experiment. What does execute faster: an immediately resolved promise or an immediate timeout (aka a timeout of 0 milliseconds)?


Promise.resolve(1).then(function resolve() {

console.log('Resolved!');

});

setTimeout(function timeout() {

console.log('Timed out!');

}, 0);

// logs 'Resolved!'

// logs 'Timed out!'


Promise.resolve(1) is a static function that returns an immediately resolved promise. setTimeout(callback, 0) executes the callback with a delay of 0 milliseconds.

Open the demo and check the console. You'll notice that 'Resolved!' is logged first, then 'Timeout completed!'. An immediately resolved promise is processed faster than an immediate timeout.

Might the promise process faster because the Promise.resolve(true).then(...) was called before the setTimeout(..., 0)? Fair enough question.

Let's change slighly the conditions of the experiment and call setTimeout(..., 0) first:


setTimeout(function timeout() {

console.log('Timed out!');

}, 0);

Promise.resolve(1).then(function resolve() {

console.log('Resolved!');

});

// logs 'Resolved!'

// logs 'Timed out!'


Open the demo and look at the console. Hm... the same result!

setTimeout(..., 0) is called before Promise.resolve(true).then(...). However, 'Resolved!' is still logged before 'Timed out!'.

The experiment has demonstrated that an immediately resolved promise is processed before an immediate timeout. The big question is... why?

2. The event loop

The questions related to asynchronous JavaScript can be answered by investigating the event loop. Let's recall the main components of how asynchronous JavaScript works.

Note: if you aren't familiar with the event loop, I recommend watching this video before reading further.

Event Loop Empty

The call stack is a LIFO (Last In, First Out) structure that stores the execution context created during the code execution. In simple words, the call stack executes the functions.

Web APIs is the place the async operations (fetch requests, promises, timers) with their callbacks are waiting to complete.

The task queue (also named macrostasks) is a FIFO (First In, First Out) structure that holds the callbacks of async operations that are ready to be executed. For example, the callback of a timed out setTimeout() — ready to be executed — is enqueued in the task queue.

The job queue (also named microtasks) is a FIFO (First In, First Out) structure that holds the callbacks of promises that are ready to be executed. For example, the resolve or reject callbacks of a fulfilled promise are 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 into the job queue or task queue, and dequeues any callback ready to be executed into the call stack.

3. Job queue vs task queue

Let's look again at the experiment from the event loop perspective. I'll make a step by step analysis of the code execution.

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


setTimeout(function timeout() {

console.log('Timed out!');

}, 0);

Promise.resolve(1).then(function resolve() {

console.log('Resolved!');

});


Event Loop

B) The call stack executes Promise.resolve(true).then(resolve) and schedules a promise resolution. resolved() callback is stored in Web APIs:


setTimeout(function timeout() {

console.log('Timed out!');

}, 0);

Promise.resolve(1).then(function resolve() {

console.log('Resolved!');

});


Event Loop

C) The promise is resolved immediately, as well the timer is timed out immediately. Thus the timer callback timeout() is enqueued to task queue, the promise callback resolve() is enqueued to job queue:

Event Loop

D) Now's the interesting part: the event loop priorities dequeueing jobs over tasks. The event loop dequeues the promise callback resolve() from the job queue and puts it into the call stack. Then the call stack executes the promise callback resolve():


setTimeout(function timeout() {

console.log('Timed out!');

}, 0);

Promise.resolve(1).then(function resolve() {

console.log('Resolved!');

});


'Resolved!' is logged to console.

Event Loop

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


setTimeout(function timeout() {

console.log('Timed out!');

}, 0);

Promise.resolve(1).then(function resolve() {

console.log('Resolved!');

});


'Timed out!' is logged to console.

Event Loop

The call stack is empty. The script execution has been completed.

4. Summary

Why an immediately resolved promise is processed faster than an immediate timer?

Because of the event loop priorities dequeuing jobs from the job queue (which stores the fulfilled promises' callbacks) over the tasks from the task queue (which stores timed out setTimeout() callbacks).