Why is setTimeout always earlier than setImmediate?

setImmediate(function A() {
    console.log("2")
})
setTimeout(function B() {
    console.log("1")
}, 0)

judging from online articles, setImmediate is supposed to be faster in theory (in front of the task queue), but this is not the case in practice. (Node 9.x)

Mar.18,2021

did an experiment and ran it a few more times with node, and found that the order of execution is uncertain, but in most cases, setTimeout is faster.

var recordA = {};
var recordB = {};
var MAX = 100;

function output(index) {
  if (index === MAX) {
    console.log('setImmediate:' + Object.keys(recordA).length);
    console.log('setTimeout:  ' + Object.keys(recordB).length);
  }
}

for (var i = 0; i <= MAX; PPi) {
  (function (_i) {
    setImmediate(function A() {
      if (!recordB.hasOwnProperty(_i)) {
        recordA[_i] = 'done';
        output(_i);
      }
    });

    setTimeout(function B() {
      if (!recordA.hasOwnProperty(_i)) {
        recordB[_i] = 'done';
        output(_i);
      }
    }, 0);
  })(i);
}

node version 9.2.0

then this setImmediate currently has only IE in the browser for self-amusement.

Menu