Efoskhi
Efoskhi

Reputation: 61

Javascript setInterval function increases speed onclick

I have a script which count downward on click, it's working fine but the problem is when the button "run" is clicked multiple times, the speed of the counter increase. I have used the "clearInterval" to remove the recent created interval, but it's still not working.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button class="run">Run</button>
<p class="show"></p>

Script

$(".run").on("click", function() {
    var myInterval;
    var decrement=5;
    clearInterval(myInterval) ;
    myInterval=setInterval(function decrementNum() {
        decrement--;
        $(".decrement").text(decrement) ;
        if(decrement==0){
            decrement=5;
        }
        $(".show").text(decrement) ;
    }, 2000)
})

Upvotes: 0

Views: 502

Answers (1)

Tushar Shahi
Tushar Shahi

Reputation: 20486

Your intervalId is local to the function. Everytime you are adding more and more event listeners. The setInterval's frequency is increasing hence its speed increases Move your variable outside so everytime you click, the myInterval accessed is the same.

var myInterval;
$(".run").on("click", function() {
    var decrement=5;
    clearInterval(myInterval) ;
    myInterval=setInterval(function decrementNum() {
        decrement--;
        $(".decrement").text(decrement) ;
        if(decrement==0){
            decrement=5;
        }
        $(".show").text(decrement) ;
    }, 2000)
})

Upvotes: 1

Related Questions