Skip to content

Incorrect Event loop callbacks execution order in a node.js project #1048

@zveroboy

Description

@zveroboy

Describe the bug

nextTick callbacks should be executed between macrotasks.

…the nextTickQueue will be processed after the current operation is completed, regardless of the current phase of the event loop. Here, an operation is defined as a transition from the underlying C/C++ handler, and handling the JavaScript that needs to be executed.

source

Immediately after every macrotask, the engine executes all tasks from microtask queue, prior to running any other macrotasks…

source

Link to the blitz that caused the error

https://stackblitz.com/edit/node-u4nbwx?file=index.js

Steps to reproduce

  1. Launch node.js project
  2. Put this code in the index.js
setTimeout(() => {
  console.log('--- Timer 1 ---');
  process.nextTick(() => {
    console.log('--- nextTick 1 ---');
  });
}, 0);

setTimeout(() => {
  console.log('--- Timer 2 ---');
  process.nextTick(() => {
    console.log('--- nextTick 2 ---');
  });
}, 0);

setImmediate(() => {
  console.log('--- setImmediate 1 ---');
});
  1. Run node index.js in the terminal
  2. You'll see incorrect execution order
~/projects/node-u4nbwx
❯ node index
--- setImmediate 1 ---
--- Timer 1 ---
--- Timer 2 ---
--- nextTick 1 ---
--- nextTick 2 ---

Expected behavior

It should print out

--- Timer 1 ---
--- nextTick 1 ---
--- Timer 2 ---
--- nextTick 2 ---
--- setImmediate 1 ---

or

--- setImmediate 1 ---
--- Timer 1 ---
--- nextTick 1 ---
--- Timer 2 ---
--- nextTick 2 ---

Parity with Local

Screenshots

Снимок экрана 2023-04-24 в 23 26 09

Снимок экрана 2023-04-25 в 01 18 28

Platform

Browser name  = Chrome
Full version  = 112.0.0.0
Major version = 112
navigator.appName = Netscape
navigator.userAgent = Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36
performance.memory = {
  "totalJSHeapSize": 63087190,
  "usedJSHeapSize": 58269934,
  "jsHeapSizeLimit": 4294705152
}
Hash = 95b70c8d

Additional context

No response

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