1

What is the difference between:

  1. await new Promise(resolve => setTimeout(resolve, 5000));

  2. await setTimeout(resolve, 5000);

variable
  • 8,262
  • 9
  • 95
  • 215
  • 2
    `await` only knows how to interact with promises, not the timer id returned by setTimeout. The `await` in the second one does pretty much nothing. – Nicholas Tower Feb 17 '22 at 21:06
  • But isn't setTimeout an async function? – variable Feb 17 '22 at 21:07
  • 1
    If by async function you mean a function that returns a promise, no, it is not. It does queue up some code to run at a later time, so it's asynchronous in that sense. – Nicholas Tower Feb 17 '22 at 21:07
  • callbacks registered with Promises are termed "microtasks" have their own Queue which is prioritized over the Queue meant for setTimeout and the likes. Checkout this excellent source https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/ – D.B.K Feb 17 '22 at 21:14
  • In example 1, is the promise put in the microtask queue? And then when promise gets chance to run in the main thread, then the set timeout is put in the macro tasks queue? – variable Feb 18 '22 at 03:42

1 Answers1

1

await setTimeout(resolve, 5000); does nothing extra, it's the same as setTimeout(resolve, 5000);

await will pause code execution of the containing function until a promise is resolved. The setTimeout function does not return a promise, it is not an async function. Hence, await is redundant, it doesn't do anything special in this case.

Your first bit of code does return a promise. It takes the legacy non-promise-based setTimeout function and turns it into a promise form. It then awaits this promise form.

You should learn about promises to gain a better understanding of what's going on. The key thing to note here is the difference between callback-based functions (like setTimeout) and modern promise-based functions.

David Callanan
  • 5,601
  • 7
  • 63
  • 105
  • But setTimeout is an async function. Doesn't await block the main thread on this line in each case? – variable Feb 17 '22 at 21:08
  • @variable Only waits for `Promise`s and `setTimeout` does not return a `Promise`. – Ruan Mendes Feb 17 '22 at 21:10
  • It depends what you define async as. If by async, you mean a function that returns a promise, then no, `setTimeout` is most certainly not async. But if by async you just mean a form of asynchronous programming, then yes, it is asynchornous, but you are treating it as if it is the other kind of async so this fact doesn't change anything. – David Callanan Feb 17 '22 at 21:10