pitizzzle
pitizzzle

Reputation: 383

Why is the Node.js Event Loop so slow on idle?

Maybe I've understood something wrong about the Event Loop, but it seems like 1000 rounds through the Event Loop take more than 1000ms.

const { performance } = require('perf_hooks');

let counter = 0;
const timestamp_start = performance.now();

increment();
function increment() {
    if (counter === 1000) {
        console.log(`${Math.round(performance.now() - timestamp_start)}ms`); // -> 1186ms
    }
    else {
        counter++;
        setTimeout(increment, 0);
    }
}

Is this expected behavior? What does the node process do all the time? xD

Upvotes: 2

Views: 1144

Answers (1)

Kaiido
Kaiido

Reputation: 136598

The thing here is that you are relying on setTimeout(fn,0) to fire as soon as possible. It isn't the case, well, it wasn't always the case at least.

In both chromium and node there used to be a 1ms minimum timeout, apparently it's in the process of being removed in chromium (https://crbug.com/402694), but I believe even the latest nodejs still has it.

A better way to hook to the event-loop without delay is to use the setImmediate method, and there you'll see your full loop takes about 20ms.

Try it online!

Upvotes: 2

Related Questions