javascript - 循环中的多个设置超时
我想读取一个文件,做一些事情,检查操作模式。
如果 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;
}
I want to read a file, do some stuff, check action mode.
If mode = STOP then delay processing until mode != STOP, otherwise repeat entire process.
I want it to keep delaying until mode changes.
The code below results in an infinite loop & browser crash:
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
一抹苦笑2025-01-09 11:27:18
我认为您没有完全理解异步代码。
没有办法以您尝试的方式“延迟”javascript(例如其他语言中的 wait
或 sleep
)。对 setTimeout
的调用不会在该点停止执行 5 秒。
尝试将 setTimeout 视为将传入函数放入队列中以便在将来某个时刻调用的请求。完成后,脚本将立即继续执行下一行代码,就像任何其他函数调用一样。
在您的示例中,类似以下内容会更有意义:
function fnDelay(){
if(mode != 'STOP'){ fnIterateGeocode(); }
else { setTimeout(fnDelay,5000);
}
只要 mode == 'STOP'
,它就会每 5 秒调用一次自身,一旦没有,它就会调用 fnIterateGeocode
。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您已将对
fnDelay
的调用放在错误的位置:您的代码当前编写的方式确实是一个无限循环(好吧,如果您没有耗尽堆栈空间,就会出现这种情况) ,因为
fnDelay
总是立即调用自身。You've put the call back to
fnDelay
in the wrong place:The way your code is current written is indeed an infinite loop (well, it would be if you didn't run out of stack space), because
fnDelay
always calls itself immediately.