javascriptsetintervalclearinterval

ClearInterval() although with ID is not working


I have a code when a timer is shown and removed using 2 functions repeatedly by using SetInterval. However when the timer is finished I am trying to clear the SetInterval With ClearInterval but this is not working. When setInterval and ClearInterval set outside gettimer function the they work properly as well. Can someone help?

let M1, M2
function ShowScrollBar(){
    ScrollContainer.classList.add('show-scroll-container')
}

function TimeShowscrollBar(){
    M1 = setInterval(ShowScrollBar,3000)
}

function RemoveScrollBar(){
    ScrollContainer.classList.remove('show-scroll-container')
}

function TimeRemovecrollBar(){
    M2 = setInterval(RemoveScrollBar,6000)
}

function ClearTimeShowscrollBar(){
    clearInterval(M1)
}

function ClearTimeRemovecrollBar(){
    clearInterval(M2)
}

function gettimer(){
const futureTimems = ClosingDate.getTime()
const presentTimems = new Date().getTime()
const RemainingTimeSec = (futureTimems-presentTimems)/1000
if(RemainingTimeSec>=0){    
    window.addEventListener('DOMContentLoaded', function(){
        popup.classList.add('showpopup')
        popup.classList.remove('popup')
       
    })
}

ClosePopupBtn.addEventListener('click',function(){
    popup.classList.remove('showpopup')
    popup.classList.add('popup')
    TimeShowscrollBar()
    TimeRemovecrollBar()
       
})

if (RemainingTimeSec<=0){
    clearInterval(countdown)
//Functions with clearInterval not working here
    ClearTimeShowscrollBar()
    ClearTimeRemovecrollBar()
    timing.forEach(function(contenu, MVindex){
        contenu.innerHTML = '00'
    })
    timingS.forEach(function(contenu, MVindex){
        contenu.innerHTML = '00'
    })
    popup.classList.remove('showpopup')
    popup.classList.add('popup')  
}
}
let countdown = setInterval(gettimer,1000)
gettimer()

Solution

  • You have quite a bit going on here that will cause a lot of problems.

    Ask yourself, what happens if the users clicks twice on the Close button? Three times? It will call setInterval for each click, but you only ever clear one of them, maybe, in the future.

    Then, what happens if you call addEventListener multiple times? You create multiple listeners, so clicking the button will act like it was clicked multiple times.

    At best, when it counts down to zero, you are only clearing 1 of several intervals you have started.

    EDIT: In case it isn't clear, you create a new listener every second in gettimer, so for every second the page has been loaded, you will create intervals.

    DON'T CREATE MULTIPLE LISTENERS. They don't remove themselves or stop listening just because you add another one or they handle a single event.