Search code examples
javascriptsettimeoutcleartimeout

clearTimeout not working in recursion function - javascript


Here is the code I am using. When ticks becomes equal to 5 the recursion function should stop clearing the mainThread timeout. Anybody please help.

var mainThread;  
var ticks = 0;  
function tickTimer() {  
    clearTimeout(mainThread);  
    if (ticks >= 5) {  
        endGame();  
    }  
    else {  
        mainThread = setTimeout(function () {  
            ticks++;  
            tickTimer();  
        }, 1000);  
    }  
}  

Let me know if any concerns. Thank you in advance.


Solution

  • you can try this. all you need to do is clear interval every time tickTimer function is called.
    
    var  mainThread = setInterval(tickTimer, 1000);
    var ticks = 0;
    
    function tickTimer() {       
        if (++ticks >= 5)  {
            clearInterval (mainThread); 
            endGame();  
        }  
    }