Skip to content

non-deterministic order of execution of setTimeout vs setImmediate #392

Description

@marzelin

The flow of execution in the event loop is strictly specified:

  • timers
  • pending callbacks
  • idle handles
  • prepare handles
  • poll for i/0
  • check handles
  • close callbacks

Hence, when we have main script:

// main_script.js
setTimeout(function timeout () {
  console.log('timeout');
},0);

setImmediate(function immediate () {
  console.log('immediate');
});

with setTimeout() callback with the 0 delay time (which makes it due initially) should be called before setImmediate() callbacks that are executed in check phase that takes place after timers phase.

But it is not so. The order is pretty random.
Is that because setTimeout() delay when set to 0 is internally converted to 1 (which may or may not be due when checked in the timers phase), or is there more factors that contribute to this non-deterministic behavior?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions