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/
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:
var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;
function checkForNewRace(){
if ( $("#data").html() == "1"){
$("#res").html("got it!");
}
else{
$("#counter").html(br);
if (br++ > 5){
clearInterval(waitForNewRace);
waitInterval += 1000;
if (waitInterval > 10000)
waitInterval = 10000;
waitForNewRace = setInterval(
checkForNewRace,
waitInterval
);
}
}
$("#tst").html(waitInterval);
}
var waitForNewRace = setInterval(
checkForNewRace,
waitInterval
);
I think this will do what you want:
var br = 0;
var waitForNewRace = setInterval(function(){
checkForNewRace();
if(++br == 9){
clearInterval(waitForNewRace);
setInterval(checkForNewRace, 3000);
}
}, 1000);
function checkForNewRace(){
if($("#data").html() == "1"){
$("#res").html("got it!");
clearInterval(waitForNewRace);
}else
$("#counter").html(br);
$("#tst").html(waitInterval);
}
You could use clearInterval:
var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;
var waitForNewRace = setInterval(checkForNewRace,
waitInterval
);
function checkForNewRace(){
console.log(waitForNewRace);
if ( $("#data").html() == "1"){
$("#res").html("got it!");
}
else{
$("#counter").html(br);
if (br++ > 9){
waitInterval = 3000;
clearInterval(waitForNewRace);
br = 0;
waitForNewRace = setInterval(checkForNewRace,
waitInterval
);
}
}
$("#tst").html(waitInterval);
}
fiddle: http://jsfiddle.net/Vyczj/5/
An alternative, just need to add two lines to your own 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){
clearInterval(waitForNewRace);
waitInterval = 3000;
waitForNewRace=setInterval(checkForNewRace,waitInterval);
}
}
$("#tst").html(waitInterval);
},
waitInterval
);
精彩评论