在我的应用程序开发中,我使用
setInterval(function() {
// some code
// runs here
}, 60000);我想以1分钟的间隔执行一些代码,在某些情况下,我的代码可能需要2-3分钟。
<execute code> - <wait 1 minute> - <execute code> - <wait 1 minute> ......so on我尝试使用setInterval函数,但注意到setInterval不等待内部代码完成。请建议我如何在javascript中实现这一点。
谢谢
发布于 2020-04-19 05:33:36
更好的方法可能是使用setTimeout递归调用作业函数
setTimeout(function jobThatRunEveryMinute() {
// run code here that may take more than one minute
someExpensiveCodeToRun()
// start another job after someExpensiveCode completes
setTimeout(jobThatRunEveryMinute, 60000);
}, 60000);发布于 2020-04-19 05:33:49
这样的东西可能对你有用,但是为什么你有一个函数需要超过1分钟的时间来返回一些东西呢?
let callCompleted = true;
setInterval(function() {
if (callCompleted) {
callCompleted = false;
// pass a call back function to update the callCompleted to true
myLongRunningFunction(function() { callCompleted = true } );
// or if `myLongRunningFunction` returns a promise
myLongRunningFunction.then(() => { callCompleted = true } );
}
}, 60000);发布于 2020-04-19 06:13:42
// adjust wait time to your liking
const waitTime = 10000
let time = 0
// so you can stop it
const totalTime = 6
function excuteCode() {
time++;
console.log(time); // <=== replace with your inner code
if (time < totalTime) {
setTimeout(() => {
excuteCode()
}, waitTime)
}
}
excuteCode();https://stackoverflow.com/questions/61296431
复制相似问题