Search code examples
javascriptjquerycountdowncountdowntimer

How to stop jquery event while working on countdown


I hardly have knowledge of jquery. I am trying to make a countdown so after searching I found the code below.

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            
            timer = duration;
        }
    }, 1000);
    
}
$('.start').on('click', function(){
    var oneMinute = 60 * 1,
        display = document.querySelector('#time');
        startTimer(oneMinute, display);
})

But the countdown repeats after one minute. Like when it goes 03, 02, 01, it again starts with 59.

How to stop it?

I want to alert message and stop timer after given minutes.


Solution

  • The setInterval function returns an identifier. Store the interval ID in a variable. This allows you to use clearInterval() to cancel the interval when required.

    function startTimer(duration, display) {
        var timer = duration, minutes, seconds;
        var interval = setInterval(function () {
            minutes = parseInt(timer / 60, 10)
            seconds = parseInt(timer % 60, 10);
    
            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;
    
            display.textContent = minutes + ":" + seconds;
    
            if (--timer < 0) {
                
                clearInterval(interval);
            }
            
        }, 1000);
        
    }
    $('.start').on('click', function(){
        var oneMinute = 5 * 1, // 5 Seconds for easy testing
            display = document.querySelector('#time');
            startTimer(oneMinute, display);
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="time">
    00:00
    </div>
    
    <button type="button" class="start">
    START
    </button>