Search code examples
javascriptjqueryfunctioncleartimeout

Javascript ClearTimeout doesnt work


I'm looking for a solution for my code. My clearTimeout function doesn't work in the stop(); and start(); functions, does anybody know how to fix this?

The stop, start and reset button have all a setTimeout function. What I would like to do is that if is clicked at one of the buttons, the other two buttons have cleartimeout. But for somehow it doesn't working right now.

var isTimerStarted;
var timeOutElse;
var timeOut;
var opnieuw;

function start() {
    clocktimer = setInterval("update()", 1);
    x.start();
    isTimerStarted = true;
    timeOutElse = setTimeout(function(){
        document.getElementById("scherm3").style.display = "block";
        document.getElementById("scherm2.2").style.visibility = "hidden";
    }, 8000)
}

function stop() {
    x.stop();
    clearInterval(clocktimer);
    isTimerStarted = false;
    timeOut = setTimeout(function(){
        document.getElementById("scherm4").style.visibility = "visible";
        document.getElementById("scherm2.2").style.visibility = "hidden"; 
    }, 4000)
}

function reset() {
    stop();
    x.reset();
    update();
    opnieuw = setTimeout(function(){
        document.getElementById("scherm3").style.display = "block";
        document.getElementById("scherm2.2").style.visibility = "hidden"; 
    }, 10000);    
    clearTimeout(timeOut);
    clearTimeout(timeOutElse);
    document.getElementById("buttontimer").value = "Start";
} 

setTimeout(start, 5000);

function toggleTimer(event) {
    if (isTimerStarted) {
        stop();
        event.target.value = 'Start';
        clearTimeout(opnieuw);
        clearTimeout(timeOutElse);
    } else {
        start();
        event.target.value = 'Stop';
        clearTimeout(opnieuw);
        clearTimeout(timeOut);
    }
 }

Solution

  • There's nothing wrong with your code, from what I can tell.

    But I think you might have forgot to remove a line from it.

    setTimeout(start, 5000); is creating timeouts after 5 seconds whatever/whenever you click a thing.

    It is what could create timing issues.

    Here's a scenario that could happen:

    • you click
    • toggleTimer() -> start() -> create timeout and interval
    • 5s later your setTimeout(start, 5000) executes and reassign your timeout and interval variables
    • you re-click
    • latest timeout and interval gets cleared, but not the first ones

    Just to be safe, you could clear, at the beginning of each of your functions, the timeouts and intervals you're creating in the said function.

    This way, you will always clear timeouts and intervals that gets created.