如何动态重新配置 setTimeout
我想知道是否有一种方法可以将 setTimeout 函数动态设置为不同的超时。
因此,例如,我每 1 秒检查一次,但如果在 10 秒内没有得到预期结果,我想“重新配置”此 setTimeout 以等待 3 秒而不是 1 秒。
这是我的代码:
var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;
var waitForNewRace = setInterval(
function checkForNewRace(){
if ( $("#data").html() == "1"){
$("#res").html("got it!");
}
else{
$("#counter").html(br);
if (br++ > 9)
waitInterval = 3000;
}
$("#tst").html(waitInterval);
},
waitInterval
);
如果您想看看这里是 jsfiddle 上提到的代码: http://jsfiddle.net/Hitman666/Vyczj/2/
I was wondering if there is a way to set the setTimeout function to different timeout on the fly.
So, for example I check something every 1 second, but if I don't get an expected result in like 10 seconds I want to "reconfigure" this setTimeout to wait 3 seconds instead of 1.
Here is my code:
var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;
var waitForNewRace = setInterval(
function checkForNewRace(){
if ( $("#data").html() == "1"){
$("#res").html("got it!");
}
else{
$("#counter").html(br);
if (br++ > 9)
waitInterval = 3000;
}
$("#tst").html(waitInterval);
},
waitInterval
);
If you want to check it out here is the mentioned code on jsfiddle: http://jsfiddle.net/Hitman666/Vyczj/2/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须停止间隔并重新开始。请参阅 jsfiddle 的此分支。
编辑:我已经在这里复制了您的代码,以防您的 jsfiddle 代码发生问题:
You have to stop the interval and restart it. See this fork of your jsfiddle.
EDIT: I've copied your code here in case something happens with your jsfiddle code:
我认为这会做你想要的:
I think this will do what you want:
您可以使用clearInterval:
fiddle:http://jsfiddle.net/Vyczj/5/
You could use clearInterval:
fiddle: http://jsfiddle.net/Vyczj/5/
另一种方法是,只需在您自己的代码中添加两行:
An alternative, just need to add two lines to your own code: