Is there a better way to execute a node.js callback at regular intervals than setInterval?

Is there a better way to execute a node.js callback at regular intervals than setInterval?

Problem

I have a node.js script that writes a stream to an array like this:

var tempCrossSection = [];

stream.on('data', function(data) {
    tempCrossSection.push(data);
});

and another callback that empties the array and does some processing on the data like this:

var crossSection = [];

setInterval(function() {
    crossSection = tempCrossSection;
    tempCrossSection = [];

    someOtherFunction(crossSection, function(data) {
        console.log(data);
    }
}, 30000);

For the most part this works, but sometimes the setInterval callback will execute more than once in a 30000ms interval (and it is not a queued call sitting on the event loop). I have also done this as a cronJob with same results. I am wondering if there is a way to ensure that setInterval executes only once per 30000ms. Perhaps there is a better solution altogether. Thanks.

Problem courtesy of: TankofVines

Solution

When you have something async, you should use setTimeout instead, otherwise if the asynchonous function takes to long you’ll end up with issues.

var crossSection = [];

setTimeout(function someFunction () {
    crossSection = tempCrossSection;
    tempCrossSection = [];

    someOtherFunction(crossSection, function(data) {
        console.log(data);
        setTimeout(someFunction, 30000);
    }
}, 30000);
Solution courtesy of: generalhenry

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *