Node Javascript time between nextTick

Curious to how long node might spend “between ticks”?  The following script gives some insight by using Node’s process.hrtime and process.nextTick (which ensures it is run as soon as event loop is able to accommodate it) vs setImmediate which runs only at a certain part of the Node event loop:

    function run_calc_average(nextFunc) {
        var counter = 0;
        var average_tick = 0;
        var current_time;

        function calc_average() {

            if (counter > 1000) {
                console.log(`average_tick: ${average_tick} ns`);
                return;
            }

            if (counter === 0) {
                current_time = process.hrtime();
                counter += 1;
                nextFunc(calc_average);
                return;
            }

            var diff = process.hrtime(current_time);
            var time_diff = diff[0] * 1e9 + diff[1];
            current_time = process.hrtime();
            var new_count = counter + 1;

            average_tick = average_tick * (counter / new_count) + time_diff * (1 / new_count);

            console.log(`${time_diff},`); //, average_tick);
            counter = new_count;

            nextFunc(calc_average);
        }

        nextFunc(calc_average);
    }

    run_calc_average(process.nextTick);
    // run_calc_average(setImmediate);

The comparison to setImmediate shows it is indeed run “sooner” in the node event loop. Interesting also are the large occasional pauses, sometimes up to 1e6 ns, 1 milli second. Presumably this is the v8 GC kicking in but it would be good to verify.

Leave a comment