我需要偶尔执行一些有效负载函数的函数,但要考虑到
- a( 有效负载功能可能需要一些时间才能完成(如超时的 AXAJ 请求(
- b(有效载荷功能可承诺
- c( 我可能想稍后停止它
为了简单起见,只需使用新的 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);
}
})()
非常感谢 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();