如何让 setInterval 等到函数执行? [英] how to make setInterval Wait until The function execute?
本文介绍了如何让 setInterval 等到函数执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 setInterval 每 100 毫秒执行一个函数
i have a setInterval that execute a function every 100 ms
问题是 setInterval 没有等到函数完全执行
the problem is the setInterval does not wait until the function completely execute
代码如下:
function Main(){
function AnyFunction(){
setTimeout(function(){
console.log('Anything');
},2000)
}
setInterval(AnyFunction,100) ;
}
Main();
在函数执行中到底发生了什么,我怎样才能让 setInterval 等到函数执行?
what happens exactly in the function execute and how can i make setInterval Wait until The function execute ?
推荐答案
const anyFunction = () => {
return new Promise((resolve, reject) => setTimeout(resolve, 2000));
}
const cycleAsync = (fn, time) => {
const timerId = setTimeout(() => {
fn()
.then(() => {
clearTimeout(timerId);
cycle(fn, time);
});
}, time);
}
cycleAsync(anyFunction, 200);
这篇关于如何让 setInterval 等到函数执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文