Could anyone explain why this happens? (setTimeout)

Could anyone explain why this runs out of order even when the timer is set to 0 seconds?

console.log('first')

setTimeout(() => {
  console.log('second')
}, 0);

console.log('third')

Because it still takes a very small amount of time to process the code within the setTimeout().

Thanks, I was watching someone use this while studying callbacks a bit, but he never explained why this happens.

Hello @Tsmithcode,
The T.L.D.R. version: “When you use setTimeout you are saying: don’t execute this now, do other things and comeback later”.

The long version:

  • There is something called Event Loop:
  • If you read the mdn setTimeout() - Web APIs | MDN page (about setTimeout) you can see that the section specifications is about the HTML Standard and not EcmaScript (JS).

  • If you read the HTML Standard ( Web API) HTML Standard you can see that:

Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.

The important part is SCHEDULES.

A video that explain this (there are a lot of videos about the event loop, timers, microtask queuing, etc. on youtube):

Cheers and happy Coding :slight_smile:

1 Like