[英]running async function once every minute
I was planning to get a data from the server every minute. 我打算每分钟从服务器获取数据。 However, if I run this code, this function is being called repeatedly. 但是,如果我运行此代码,则会重复调用此函数。 On the other hand, if I added date.getMilliseconds == 0
in the condition, it won't process any results. 另一方面,如果我在条件中添加了date.getMilliseconds == 0
,它将不会处理任何结果。 Do you have any suggestions on how to run the function once every 1 minute? 您是否对每1分钟运行一次功能有任何建议?
async update() {
var date = new Date();
if (date.getSeconds() == 0) {
var newdata = await getData(1);
array.shift();
array.push(newdata);
}
}
Since it looks like you don't have fine control over when update
is called, one option would be to set a boolean to true
every time getSeconds() === 0
(set it to false
otherwise), and then only run the real code when the flag is false
and getSeconds() === 0
: 由于看起来您对调用update
没有很好的控制,因此一个选择是,每次getSeconds() === 0
时将布尔值设置为true
getSeconds() === 0
否则将其设置为false
),然后仅运行real标志为false
且 getSeconds() === 0
时的代码:
let hasRun = false;
// ...
async update() {
var date = new Date();
const secs = date.getSeconds();
if (secs !== 0) {
hasRun = false;
} else if (secs === 0 && hasRun === false) {
hasRun = true;
// your code
var newdata = await getData(1);
array.shift();
array.push(newdata);
}
}
An alternative that might require less resources due to not creating Date
s every frame would be to have a separate function that toggles the boolean, set with a setInterval
that runs every 60 seconds, no Date
s involved: 由于不每帧都不创建Date
,因此可能需要较少资源的替代方法是具有一个单独的函数来切换布尔值,设置为每60秒运行一次setInterval
,不涉及Date
:
let hasRun = false;
setInterval(() => hasRun = false, 60000);
async update() {
if (hasRun) return;
hasRun = true;
// your code
}
(of course, you could also try setInterval(update, 60000)
if the framework allows it) (当然,如果框架允许,您也可以尝试setInterval(update, 60000)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.