如何在回调执行结束时开始的时间间隔内运行 Javascript 函数?

如何在回调执行结束时开始的时间间隔内运行 Javascript 函数?

问题描述:

我使用 setinterval 函数在 Javascript 中异步运行一个函数.

I run a function in Javascript asynchronously by using the setinterval function.

myVar = setInterval(myTimer, 5000);

myTimer 函数的执行时间可能会很长,有时比指定的延迟时间还要长,在这种情况下,间隔只是背靠背执行.我希望回调函数的下一次执行与上一次执行的结束有关.重申一下,我希望 myTimer 函数在上一次完成后 5000 毫秒后运行,并希望重复此操作.

The execution of the myTimer function can be quite long, sometimes longer than the specified delay, in that case the intervals just get executed back to back. I would like the next execution of the callback function to be scheduled in relationship with the end of the execution of the previous. To restate I want the myTimer function to run after 5000 ms of when previous finishes and wanted this to repeat.

是的,可以使用 setTimeout 代替.

Yes this can be done using setTimeout instead.

function myTimer(){
   console.log("Exec func");
   // Rest of the functionality here
   setTimeout(myTimer, 5000);
}

myTimer();