0

我有一个 node.js 脚本,它将流写入这样的数组:

var tempCrossSection = [];

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

以及另一个清空数组并对数据进行一些处理的回调,如下所示:

var crossSection = [];

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

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

在大多数情况下这是可行的,但有时 setInterval 回调将在 30000 毫秒的间隔内执行多次(并且它不是坐在事件循环上的排队调用)。我也将其作为具有相同结果的 cronJob 完成。我想知道是否有办法确保 setInterval 每 30000 毫秒只执行一次。也许有一个更好的解决方案。谢谢。

4

2 回答 2

0

当你有异步的东西时,你应该使用 setTimeout ,否则如果异步函数需要很长时间,你最终会遇到问题。

var crossSection = [];

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

    someOtherFunction(crossSection, function(data) {
        console.log(data);
        setTimeout(someFunction, 30000);
    }
}, 30000);
于 2013-03-29T20:33:57.750 回答
0

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.

于 2013-03-29T20:36:30.427 回答