Search code examples
jquerytimerclearinterval

Clear interval timer in seconds, a real beginner in Jquery


Having some issues trying to clear interval in my code. I just need to stop it as soon as it reaches 0. I've tried setting it inside a function, also, by declaring clearInterval as a variable, but I'm feeling more confused every time as I'm not seeing any errors when console logging. What am I doing wrong here? Thanks in advance. Here is what I'm doing:

var timer = 10;
$("#timer").html("Timer");


function timerStart() {
    timer--;
    $("#timer").html(timer);
}

var intervalId = setInterval(timerStart, 1000);

if(timerStart === 0) {
    clearInterval(intervalId);
}

Solution

  • You're pretty close!

    I made a few changes:

    1. Moved the variable declarations together
    2. Instead of manually setting the .html() for the initial value, just call timerStart(). Then you can decrement it afterwards.
    3. Do the timer check right inside the timerStart() method.

        var timer = 10;
        var intervalId = null;
    
        function timerStart() {
          $("#timer").html(timer);
          if (timer === 0) {
              clearInterval(intervalId);
          }
          timer--;
        }
    
        timerStart();
        intervalId = setInterval(timerStart, 1000);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="timer"></div>