问题
I run a function in Javascript asynchronously by using the setinterval function.
myVar = setInterval(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.
回答1:
Yes this can be done using setTimeout
instead.
function myTimer(){
console.log("Exec func");
// Rest of the functionality here
setTimeout(myTimer, 5000);
}
myTimer();
回答2:
You can do something like that:
function longFunction() {
// Do your stuff here
}
var taskId;
function task() {
longFunction();
taskId = setTimeout(task, 5000);
}
来源:https://stackoverflow.com/questions/59822925/how-do-you-run-a-javascript-function-in-an-interval-that-starts-at-the-end-of-ca