How to stop setInterval inside a function using Event Listener in JS

45 Views Asked by At

I created a countdown timer function for a bank application wherein this timer will start the countdown once the user started login into the application.

//TIMEOUT TIMER FUNCTION
const timeOutTimer = () => {
    const tick = () => {
        const minute = time / 60;
        const second = time % 60;
        time--;
        labelTimer.textContent = `${String(Math.trunc(minute)).padStart(2, 0)}:${String(second).padStart(2, 0)}`;
        console.log(`${String(Math.trunc(minute)).padStart(2, 0)}:${String(second).padStart(2, 0)}`);
        if (time === 0) {
            clearInterval(timer);
        }
    };
    
    let time = 10;
    const timer = setInterval(tick, 1000);
}

//LOGIN BUTTON FUNCTION
btnSignIn.addEventListener('click', (e) => {
    e.preventDefault();
    //Timer initiate
    timeOutTimer();
})

Is there a way to stop the timer from a different function? in my case, I want to stop the timer function once the user clicked the logout button.

btnLogOut.addEventListener('click', () => {
    //Function to be executed to stop the timer function.
})
1

There are 1 best solutions below

0
Florent M. On

The only way to do that is to keep a reference of the timer in a parent scope so it can be initialized on timeOutTimer and cleared in your event listener.

Something like this :

let timer;

const timeOutTimer = () => {
    const tick = () => {
      // Your tick method
    };
    let time = 10;
    timer = setInterval(tick, 1000);
}

btnLogOut.addEventListener('click', () => {
    clearInterval(timer);
})