0

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.

Manish Gupta
  • 1,405
  • 14
  • 32
  • You are decreasing the value of `ticks` yet expect the game to end if the value becomes larger or equal than 5. – UweB Feb 12 '14 at 08:56
  • as @UweB mentioned, shouldn't the ```if``` condition be ```if ( ticks == 5 ) { endGame(); }``` because ```(ticks >= 5)``` will always return true? – Varinder Feb 12 '14 at 08:58
  • 1
    Consider using [`setInterval`](http://stackoverflow.com/q/729921/7586) instead of calling `setTimeout` repeatedly. – Kobi Feb 12 '14 at 08:59

6 Answers6

4

Try this instead:

function tickTimer() {       
    if (++ticks >= 5)  {
        clearInterval (mainThread); 
        endGame();  
    }  
} 

var  mainThread = setInterval(tickTimer, 1000);
var ticks = 0;
loxxy
  • 12,990
  • 2
  • 25
  • 56
1

Did you declare mainThread ? Like this

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

And ticks++ not ticks--

ducdhm
  • 1,954
  • 15
  • 26
1

Please try to replace ticks-- to ticks++

Eddy
  • 88
  • 1
  • 8
1
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();  
    }  
} 
Sheelpriy
  • 1,675
  • 17
  • 28
0

I've think just send your timer as argument

function tickTimer(timer) {  
    timer && clearTimeout(timer);  
    if (ticks >= 5) {  
        endGame();  
    }  
    else {  
        var timer = setTimeout(function () {  
            ticks--;  
            tickTimer(timer);  
        }, 1000);  
    }  
}  

Don't use global scope )))

Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37
0

I thing you should Initialize variable ticks as the function is triggered.

Rohit Nigam
  • 708
  • 8
  • 23