Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why Promis is faster than setTimeout ()?

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge of "why Promis is faster than setTimeout ()". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Experiment

Let's do an experiment first: let's see which performs faster, immediate Promis or immediate timeout (0 millisecond timeout).

Promise.resolve (1) .then (function resolve () {console.log ('Timed outposts');}); setTimeout (function timeout () {console.log ('Timed outposts');}, 0); / / logs' Resolvedwaters'/ / logs' Timed outposts'

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

Open the execution console and check. You will see that the log is printed with 'Resolved accounts' and then 'Timeout completed posts'. The promise of immediate resolution is faster than immediate timeout.

Because of Promise.resolve (true). Then (...) It was called before setTimeout (..., 0), so will the promise process be faster?

Let's modify the experimental conditions and first call setTimeout (..., 0):

SetTimeout (function timeout () {console.log ('Timed outposts');}, 0); Promise.resolve (1) .then (function resolve () {console.log ('Resolvedness');}); / / logs' Resolvedness'/ / logs' Timed outflows'

Execute and view the console, and the result is the same!

Although setTimeout (..., 0) is in Promise.resolve (true). Then (...) It was called before, but 'Resolvedwaters' Still in 'Timed outposts' It was output before.

Experiments show that the promise that is resolved immediately is processed before the immediate timeout. So... Why is that?

Event cycle

Questions related to asynchronous JavaScript can be answered by exploring the event loop. Let's first review how asynchronous JavaScript works.

Empty event loop

The call stack (call stack) is the structure of the LIFO (last-in, first-out) that stores the execution context created during code execution. In short, the call stack execution is used for functions.

Web API is an asynchronous operation (fetch request, promises, timer), and the callback waits for the work here to be finished.

* * Task queue (task queue) * * is a FIFO (first-in, first-out) structure that contains callbacks for asynchronous operations ready to be performed. For example, the callback (ready for execution) of the timed-out setTimeout () enters the task queue.

The work queue (job queue) is a FIFO (first-in, first-out) structure that contains callbacks to the promise that are ready for execution. For example, a resolved resolve or a callback that refuses to enter the work queue.

Finally, the event loop (event loop) always monitors whether the call stack is empty. If the call stack is empty, the event loop looks for the work queue or task queue and dequeues the callback ready for execution to the call stack.

Work queue and task queue

Let's take a look at the previous experiment from the point of view of the event loop. I will analyze the execution of the code step by step.

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

SetTimeout (function timeout () {console.log ('Timed outbound');}, 0); Promise.resolve (1) .then (function resolve () {console.log ('Resolvedoring');})

Event cycle

(2) the call stack executes Promise.resolve (true). Then (resolve) and "arranges" a promise parsing. The resolved () callback is stored in Web API:

SetTimeout (function timeout () {console.log ('Timed outbound');}, 0); Promise.resolve (1) .then (function resolve () {console.log ('Resolvedoring');})

Event cycle

(3) the promise will solve the problem immediately, and the timer will run out immediately. At this time, the timer callback timeout () is "queued" to the task queue, and the promise callback resolve () is "queued" to the work queue:

Event cycle

(4) here is the most interesting part: the priority of the event loop puts work above tasks. The event loop causes the promise callback resolve () to dequeue from the work queue and put it on the call stack, and then the call stack executes the promise callback resolve ():

SetTimeout (function timeout () {console.log ('Timed outbound');}, 0); Promise.resolve (1) .then (function resolve () {console.log ('Resolvedoring');})

'Resolvedbirds' Is output to the console.

Event Loop

Finally, the event loop moves the timer callback timeout () from the task queue to the call stack. Then call the stack execution timer to call back timeout ():

SetTimeout (function timeout () {console.log ('Timed outbound');}, 0); Promise.resolve (1) .then (function resolve () {console.log ('Resolvedoring');})

'Timed outposts' Output to the console.

Event Loop

The call stack is empty at this time. Script execution completed.

This is the end of the content of "Why Promis is faster than setTimeout ()". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report