setInterval考虑了运行的功能时间

问题描述 投票:0回答:2

我需要偶尔执行一些有效载荷功能的功能,但要考虑到这一点

  • a)有效载荷函数可能需要一些时间才能完成(如超时的axaj请求)
  • b)有效载荷函数可以是Promise
  • c)我可能想在一段时间后停止它
javascript
2个回答
2
投票

为方便起见,只需使用新的ESnext async / await语法即可轻松完成。起初我们需要一个小助手计时器:

const time = ms => new Promise(res => setTimeout(res, ms));

要像这样使用:

(async function(){
   while(true){
       await whatever(); // whatever shall be a promise
       //wait some time:
       await time(1000);
   }
})()

0
投票

非常感谢https://www.thecodeship.com/web-development/alternative-to-javascript-evil-setinterval/和我的小改进,我发布这个解决方案,随时纠正我。

function interval(func, wait, times) {
  var _interval = function () {
    if (typeof times === "undefined" || times-- > 0) {
      try {
        Promise.resolve(func())
          .then(() => { window.setTimeout(_interval, wait) });
      }
      catch (e) {
        times = 0;
        throw e.toString();
      }
    }
  };

  _interval();

  return { stop: () => { times = 0 } };
};

interval()使用stop字段返回对象,因此您可以运行它来停止计时器,如:

let timer = interval(func, 1000, 10);
...
timer.stop();
© www.soinside.com 2019 - 2024. All rights reserved.