Node.js: callTimeout calls for the same delay caused synchronously?

I have the following code to demonstrate the problem:

let count = 5;
while (count--) {
    setTimeout(() => {
        console.log('timeout');
        process.nextTick(() => {
            console.log('tick');
        });
    }, 0);
}

const largeNumber = 20000;
for (let i = 0; i < largeNumber; i += 1) {
    for (let j = 0; j < largeNumber; j += 1) {
        // do nothing here, just be sure all the setTimeout callbacks are in the queue when exiting sync code
    }
}

The result that I expect is as follows:

timeout
tick
timeout
tick
timeout
tick
timeout
tick

Since the event loop checks the queue timeouts, it detects the first callback setTimeout, starts it, and checks the queue nextTickafter. And for further callbacks setTimeouthe has to do the same.

But I get the following output:

timeout
timeout
timeout
timeout
timeout
tick
tick
tick
tick
tick

Why?

+4
source share
2 answers

setTimeoutand nextTickwill put the function in the function queue for calling later.

When the JavaScript event loop is not busy with anything else, it will look at this function queue to see if they should be executed.

, nextTick (- ).

- , setTimeout , ( ).

+2

, , .

node.js :

process.nextTick() queue ". , , , , .

setTimeout (fn, 0). . / ( ) .

, , - .

timeout . callstack .

:

:

  • ( )
  • -
  • -
  • -
  • -
  • -
  • -
  • n times timeout

, , , , .

:

  • -
  • -
  • -
  • -
  • -
  • -
  • n times timeout
  • -
  • -
  • -
  • tick n

, .

+1

Source: https://habr.com/ru/post/1696151/


All Articles