Reputation: 303
I have a problem with set and clear Timeout in javascript. I want to set var test2 as a backup for var test but if test works I have to delete the test2
var timeSec=2000;
var test = setTimeout(function() {
clearTimeout(test2);
jQuery('.next',curdoc)[0].click();
}, timeSec);
var test2 = setTimeout(function() {
// do something else
}, timeSec+timeSec);
Upvotes: 0
Views: 252
Reputation: 102
Why don't you try with try-catch?.
var test = setTimeout(function() {
try {
jQuery('.next',curdoc)[0].click();
}
catch(err) {
setTimeout(function() {
alert('fallback');
}, timeSec+timeSec);
}
}, timeSec);
Upvotes: 1
Reputation: 2644
The first thing test
does is clearing the test2
timeout. This will happen after timeSec
. test2
will never get executed because it will run after timeSec * 2
but gets cleared half time in.
You should clear test2
only after successful execution of whatever test
is going to do.
var timeSec=2000;
var test = setTimeout(function() {
jQuery('.next',curdoc)[0].click();
if(successful()) {
clearTimeout(test2);
}
}, timeSec);
var test2 = setTimeout(function() {
// do something else
}, timeSec+timeSec);
Upvotes: 2