最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Run async function every n seconds, wait if async function takes longer than n seconds - Stack Overflow

programmeradmin4浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 8

I 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);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论