I want an asynchronous function to run at a maximum rate of once a second.
async function update(){
await wait_for_response();
}
setInterval(update, 1000);
In the above code, if the function takes longer than a second, the next update begins before the last has finished.
If update() takes longer than 1 second, I want the next update to wait until the last update is finished, running immediately afterwards.
Is there a simple built-in method or standard practice for implementing this?
I want an asynchronous function to run at a maximum rate of once a second.
async function update(){
await wait_for_response();
}
setInterval(update, 1000);
In the above code, if the function takes longer than a second, the next update begins before the last has finished.
If update() takes longer than 1 second, I want the next update to wait until the last update is finished, running immediately afterwards.
Is there a simple built-in method or standard practice for implementing this?
Share Improve this question asked Sep 12, 2019 at 20:12 hedgehog90hedgehog90 1,51120 silver badges37 bronze badges2 Answers
Reset to default 8I think that setTimeout
would be a better choice in this case:
async function update() {
const t1 = new Date();
await wait_for_response();
setTimeout(update, Math.max(0, 1000 - new Date + t1));
}
update();
This simple construct using promise chaining can handle it for you:
let lastPromise = Promise.resolve();
function update() {
lastPromise = lastPromise.then(wait_for_response, wait_for_response);
}
setInterval(update, 1000);
If we're worried about the chain growing unbounded, we can use this version:
let lastPromise = Promise.resolve();
function update() {
const p = lastPromise;
function cleanup() {
if (lastPromise === p) {
lastPromise = Promise.resolve();
}
}
lastPromise = lastPromise
.then(wait_for_response, wait_for_response)
.then(cleanup, cleanup);
}
setInterval(update, 1000);