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

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.

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);

Timers in javascript are not as reliable as many think. It sounds like you found that out already! The key is to measure the time elapsed since the last invocation of the timer's callback to decide if you should run in this cycle or not.

See http://www.sitepoint.com/creating-accurate-timers-in-javascript/

The ultimate goal there was to build a timer that fires, say every second (higher precision than your timeout value), that then decides if it is going to fire your function.