while 循环在 node.js 中没有得到更新的全局变量
While loop does not get updated global variable in node.js
我试图每 5 秒将数据保存到一个数组中。首先,我尝试了这个:
setInterval(function() {
data.push({
price: getCurrentPrice(),
time: moment().format()
})
}, 5000);
在 运行 整整 30 分钟后,setInterval 方法延迟了 1 秒,这对我的用例来说是无法忍受的,所以我使用 moment.js 库尝试了一些不同的东西:
while(true){
if(moment().diff(lastSaveTime, 'seconds')==5){
lastSaveTime = moment();
data.push({
price: getCurrentPrice(),
time: lastSaveTime.format()
})
}
}
在无限循环中,如果最后一次数据保存时间早于 5 秒,则保存数据。这很好用,但是有一个问题:
While 循环没有得到 getCurrentPrice() 应该 return 的更新值。它 return 与无限 while 循环中的值相同。有什么解决办法吗?
写这样一个无限循环不是一个好主意,因为这会阻塞事件循环,并且不允许其他任何东西运行。
我会推荐使用这样的东西https://gist.github.com/tanepiper/4215634
既然提到它是针对 NodeJs 的,您可以使用一些已经解决计时器不准确问题的 npm 模块。例如 https://github.com/aduth/correctingInterval or https://github.com/klyngbaek/accurate-interval
我试图每 5 秒将数据保存到一个数组中。首先,我尝试了这个:
setInterval(function() {
data.push({
price: getCurrentPrice(),
time: moment().format()
})
}, 5000);
在 运行 整整 30 分钟后,setInterval 方法延迟了 1 秒,这对我的用例来说是无法忍受的,所以我使用 moment.js 库尝试了一些不同的东西:
while(true){
if(moment().diff(lastSaveTime, 'seconds')==5){
lastSaveTime = moment();
data.push({
price: getCurrentPrice(),
time: lastSaveTime.format()
})
}
}
在无限循环中,如果最后一次数据保存时间早于 5 秒,则保存数据。这很好用,但是有一个问题:
While 循环没有得到 getCurrentPrice() 应该 return 的更新值。它 return 与无限 while 循环中的值相同。有什么解决办法吗?
写这样一个无限循环不是一个好主意,因为这会阻塞事件循环,并且不允许其他任何东西运行。
我会推荐使用这样的东西https://gist.github.com/tanepiper/4215634
既然提到它是针对 NodeJs 的,您可以使用一些已经解决计时器不准确问题的 npm 模块。例如 https://github.com/aduth/correctingInterval or https://github.com/klyngbaek/accurate-interval