Search code examples
javascriptnode.jssettimeoutmessage-queueevent-loop

when is the callback passed to setTimeout put on the message queue?


setTimeout(callback, 1000)

Is callback put on the message queue after 1000ms or is it put to the message queue immediately?

If it is put to the message queue after 1000ms, then does that mean that the 1000 does not mean that the callback will run in 1000, but instead it means that the callback may be run at a minimum only after 1000?


Solution

  • Is callback put on the message queue after 1000ms or is it put to the message queue immediately?

    After 1000ms - that's when the timer runs out. If it was put on the message queue immediately, there would be no waiting before is run.

    If it is put to the message queue after 1000ms, then does that mean that the 1000 does not mean that the callback will run in 1000, but instead it means that the callback may be run at a minimum only after 1000?

    Yes, if the event loop is still busy with other tasks (especially long-running blocking code) at that time, it will have to wait for those to finish. The message queue is a queue, it is serviced one task after the other; no two callbacks are executed in parallel.

    (Notice that setTimeout is allowed to lag arbitrarily anyway).