Search code examples
javascriptjquerysettimeoutcleartimeout

2 setTimeout function the first one clears the second one javascript


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);

Solution

  • 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);