我想读取一个文件,做一些事情,检查操作模式。
如果 mode = STOP,则延迟处理,直到 mode != STOP,否则重复整个过程。
我希望它继续延迟,直到模式改变。
下面的代码会导致无限循环和浏览器崩溃:
function fnIterateGeocode(addressVariations) {
// read a file & do some stuff
// check for delay
fnDelay();
// if not end of file then Iterate
if (nextRecord.EOF != 'Y') {
setTimeout(function(){
fnIterateGeocode(addressVariations);
}
, 5000);
}
// if mode = STOP, then delay for 5 seconds and check again
function fnDelay(){
if(mode == 'STOP'){
setTimeout(function(){
}
, 5000);
fnDelay();
}
return;
}
return;
}
最佳答案
您将 fnDelay
的调用放错了位置:
function fnDelay(){
if(mode == 'STOP'){
setTimeout(function(){
// It should be here
}
, 5000);
fnDelay(); // Not here
}
return;
}
您的代码当前编写的方式确实是一个无限循环(好吧,如果您没有用完堆栈空间,就会出现这种情况),因为 fnDelay
总是立即调用自身。
关于javascript - 循环中的多个设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9116834/