Search code examples
javascriptsetinterval

How to clear setInterval in a Function


Hello I have a problem.

Does anyone know, why my "clearInterval" dont work after click?

"use strict";
let activeCount = 0;
let switcher = document.getElementById("counter__switcher");
let counter = document.getElementById("counter__number");

counter.innerText = "0";
let parsed = parseInt(counter.innerText);

switcher.addEventListener("click", function(e) {
    if(activeCount == 0) {
    counter.classList.toggle("d-block");
    e = setInterval(function() {
        counter.innerText = parsed++;
    },1000)
    activeCount = 1;
    console.log(activeCount)
    }
    else {
        window.clearInterval(e);
    }
})

Solution

  • You are doing a lot of things wrong here.

    Firstly the variable e has the event data stored in (like the coordinates of the click), so you shouldn't reassign it to carry another unrelated value. Secondly since you are accessing it inside a callback function, you need to keep in mind two things, first the variable containing the timeout should be global and should not be assigned some other value.

    In your example the variable e containing the timeout is destroyed / garbage collected once the function finishes. And when the callback function is run again, the variable e carries the event object, wand not a timeout that can be passed to clearInterval.

    To do it correctly declare a global variable using let someTimeout; and assign it the value or call clearInterval in the callback function accordingly.

    Here is an edited example:

    "use strict";
    let activeCount = 0;
    let switcher = document.getElementById("counter__switcher");
    let counter = document.getElementById("counter__number");
    let myTimeout;
    
    counter.innerText = "0";
    let parsed = parseInt(counter.innerText);
    
    switcher.addEventListener("click", function(e) {
        if(activeCount == 0) {
        counter.classList.toggle("d-block");
        myTimeout = setInterval(function() {
            counter.innerText = parsed++;
        },1000)
        activeCount = 1;
        console.log(activeCount)
        }
        else {
            window.clearInterval(myTimeout);
        }
    })