コードにはいくつかの問題があります。まず第一に、あなたは多くの状態に共有しています。たとえば、crossSection は無名の Interval 関数でのみ定義する必要があります。「crossSection」がクロージャーとして定義されているのはなぜですか? someOtherFunction が長時間実行されると、ある種の競合状態に陥る可能性があります。
var source = [];
stream.on('data', function(data) {
source.push(data);
});
setInterval(function() {
var target = source;
source = [];
someOtherFunction(target, function(data) {
console.log(data);
}
}, 30000);
someOtherFunctionにアクセスできる場合は、このようにすべてを書き直します
var source = [];
stream.on('data', function(data) {
source.push(data);
});
setInterval(function() {
var processing = true;
while (processing) {
var elem = source.shift();
someOtherFunction(elem, function(data) {
console.log(data);
});
processing = checkForBreakConditionAndReturnFalseIfBreak();
}
}, 30000);
それでも、要素の数が多すぎてsomeOtherFunctionsに時間がかかりすぎると、問題が発生する可能性があります。だから私はおそらくこのようなことをするでしょう
var source = [];
var timerId = 0;
stream.on('data', function(data) {
source.push(data);
});
function processSource() {
clearTimeout(timerId);
var processing = true;
while (processing) {
var elem = source.shift();
someOtherFunction(elem, function(data) {
console.log(data);
});
processing = checkForBreakConditionAndReturnFalseIfBreak();
}
setTimeout(processSource, calcTimeoutForNextProcessingDependentOnPastData());
};
setTimeout(processSource, 30000); //initial Timeout