Promise vs setTimeout

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


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)


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.


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