Promise vs setTimeout

JavascriptAsynchronous

Javascript Problem Overview


I've observed that in the following code:

setTimeout(function(){console.log('setTimeout')});
Promise.resolve(1).then(function(){console.log('promise resolve')})

No matter how many times I execute this, the promise callback always logs before the setTimeout.

My understanding is that both callbacks are scheduled to be executed to the next tick, and I don't really understand what is going on that makes the promise always take precendence over the timeout.

Javascript Solutions


Solution 1 - Javascript

Promise.resolve schedules a microtask and the setTimeout schedules a macrotask. And the microtasks are executed before running the next macrotask.

Solution 2 - Javascript

Short answer Promises have better priority than setTimeout callback function in event loop stack(or how i understand it).

Long answer watch this video. Very helpful. Hope this helps.

https://www.youtube.com/watch?v=8aGhZQkoFbQ

Thanks @MickJuice for new and updated video for event loop.

https://www.youtube.com/watch?v=cCOL7MC4Pl0

Solution 3 - Javascript

setTimeout() has a minimum delay of 4ms, so even though you didn't specify a delay in your code the timeout will still be delayed at least 4ms. Your promise's .then() is called in the meantime.

Solution 4 - Javascript

Timeouts and Promises both serve to execute code in an asynchronous way but with differences characteristics and purposes:

setTimeout

  • Delays the execution of a function by specific time duration.
  • Does not block the rest of the code execution (asynchronous behavior)
  • They create Macrotask (browser internal operation)

Promises

  • They are a wrapper to allow asynchronous execution of code(Eg: an ajax call). (Does not depend on specific time duration)
  • They are especially useful to chain different async calls.
  • Does not block the rest of the code execution (asynchronous behavior) at less you are using the await operator.
  • They create Microtask (browser internal operation), which have priority over the Macrotask.

Recommendation

  • Use setTimeout when you want to delay a function execution some specific time duration and not block the rest of the code execution in the process

  • Use Promises: When you want to execute some async code and to avoid the “callback hell” (yes because you can make asynchronous ajax calls without Promises but the syntax is less clear and more prone to errors)

Solution 5 - Javascript

This has to do with the event loop as defined in the Web Spec. The browser has multiple task queues for multiple types of tasks (e.g. timer tasks created through setTimeout), as well as a microtask queue (where Promise settlement gets pushed to). Whenever the browser finishes executing a task, it empties the microtask queue and executes all tasks in it, before continuing with a task from another task queue.

Therefore after the code executes (which is a task), the Promise settlement is inside of the microtask queue, and the timer task might already be inside a task queue¹. The microtask queue gets emptied and the Promise resolves. Then somewhen the timer task runs.

¹ Browsers might choose to increase timeouts a bit, and they do. A timeout will never run after 0ms in most browsers.

Solution 6 - Javascript

Timeouts and Promises serve different purposes.

setTimeout delays the execution of the code block by a specific time duration. Promises are an interface to allow async execution of code.

A promise allows code to continue executing while you wait for another action to complete. Usually this is a network call. So anything in your then() call will be executed once the network call (or whatever the promise is waiting for) is completed. The time difference between the start of the promise and the resolution of the promise entirely depends on what the promise is executing, and can change with every execution.

The reason the promise is executing before your timeout is that the promise isn't actually waiting for anything so it resolved right away.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionweiskView Question on Stackoverflow
Solution 1 - JavascriptMohamed GaraView Answer on Stackoverflow
Solution 2 - JavascriptMykola BorysyukView Answer on Stackoverflow
Solution 3 - JavascriptnnnnnnView Answer on Stackoverflow
Solution 4 - JavascriptJuanma MenendezView Answer on Stackoverflow
Solution 5 - JavascriptJonas WilmsView Answer on Stackoverflow
Solution 6 - JavascriptjfadichView Answer on Stackoverflow