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?


setTimeout(() => {
}, 0);


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:

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

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.