Search code examples
javascriptcleartimeout

clearTimeout not working: parameter undefined(even though it's defined in the global scope)


My setTimeout() function works, but my clearTimeout() is not working. Even though I have an 'if' statement that's supposed to run the clearTimeout function once my variable 'secs' is less than 0, the timer keeps counting down into negative numbers. When I type my variable name, 'secs' into the console, I get undefined, even though it's defined as a parameter in the function called by my setTimeout. I don't know what I'm doing wrong. Can anyone help, please?

My full code is at https://codepen.io/Rburrage/pen/qBEjXmx;

Here's the JavaScript snippet:

function startTimer(secs, elem) {
    t = $(elem);
    t.innerHTML = "00:" + secs;

    if(secs<0) {
        clearTimeout(countDown);
    }
    secs--;
    //recurring function
    countDown = setTimeout('startTimer('+secs+',"'+elem+'")', 1000);

}

Solution

  • Add a condition to call recursive function like below.

    if (secs < 0) {
    
       secs = secsInput;
     }
    
       //recurring function
        countDown = setTimeout('startTimer('+secs+',"'+elem+'")', 1000);