سؤال

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.

هل كانت مفيدة؟

المحلول 2

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

نصائح أخرى

Try this instead:

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

var  mainThread = setInterval(tickTimer, 1000);
var ticks = 0;

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

Please try to replace ticks-- to ticks++

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

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top