Search code examples
javascriptjquerytimercountdown

Stop jQuery timer at 0 using clearInterval


I'm having issues using clearInterval to stop my simple count timer once it is equal to 0. Essentially, timer goes past 0 into negative values instead of stopping at 0. I am creating a basic quiz that ideally will alert the user of the correct answers once the timer reaches and stops at 0.

Below is current code:

var count = 10;
var gameTime;

gameTime = setInterval("counter()", 1000);

function convertSeconds(s){
    var min = Math.floor(s / 60);
    var sec = s % 60;
    return min + ":" + sec;
}

function counter(){
count--;
$("#timer").text(convertSeconds(count));
}

if (count === 0) {
    clearInterval("#timer");
} else {
    //Do nothing
}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Trivia</title>
	<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>



</head>
<body>
<div id ="timer">10</div>
</body>


Solution

  • Just move your if check into the counter function and clear the gameTime variable.

    setInterval runs the provided function at the given interval so anything you want to run or check on that interval must happen in the provided function.

    var count = 10;
    var gameTime;
    
    gameTime = setInterval("counter()", 1000);
    
    function convertSeconds(s){
        var min = Math.floor(s / 60);
        var sec = s % 60;
        return min + ":" + sec;
    }
    
    function counter(){
    count--;
    $("#timer").text(convertSeconds(count));
    if (count === 0) {
        clearInterval(gameTime);
    } else {
        //Do nothing
    }
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>Trivia</title>
    	<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
    
    
    
    </head>
    <body>
    <div id ="timer">10</div>
    </body>