How do you run a Javascript function in an interval that starts at the end of callback execution?

荒凉一梦 提交于 2021-02-10 21:01:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!