Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

401
Visualizações
clearInterval not working (vanilla javascript)

Here's the setup. I'm looking to stop the looper (setInterval()) from running after 5 seconds.

I have lots of comments so it should be fairly easy to understand, just ask me any questions for clarification.

I have tried moving the if statement (that checks the timer value === 5000) around. Tried it inside the setInterval function, tried in the onClick function.

I have also tried running setInterval() and clearInterval() preffixed with window.

Any ideas folks? 🙏🏼 🥺

window.onload = function(){
    
    var looper;
    var degrees = 0;
    var timer = 0; // timer used to monitor how long the wheel has been spinning

    function startWheelAnimation(elementId, speed){
        // 1. get the element to rotate
        const ele = document.getElementById(elementId); // get the HTML element to rotate
        const cssRotateVal = "rotate("+degrees+"deg)"; // the CSS style rotate value
        
        // 2. CSS3 browser compatibility checks
        if(navigator.userAgent.match("Chrome")){
            ele.style.WebkitTransform = cssRotateVal;
        } else if(navigator.userAgent.match("Firefox")){
            ele.style.MozTransform = cssRotateVal;
        } else if(navigator.userAgent.match("MSIE")){
            ele.style.msTransform = cssRotateVal;
        } else if(navigator.userAgent.match("Opera")){
            ele.style.OTransform = cssRotateVal;
        } else {
            ele.style.transform = cssRotateVal;
        }
        
        // 3. start looping at the rate of speed var
        looper = setInterval( ()=>{
            // at the rate of speed var run the following code
            startWheelAnimation( elementId, speed );
        }, 
        speed);
        
        degrees++; // increment the degrees value by 1
        timer++; // increment the timer value by 1
        console.log(timer); // devtool

        if( degrees > 359 ){ // reset the degrees value back to 0 upon a full rotation
            degrees = 0;
            clearInterval(looper); // stop the wheel spinning
        }

        if( timer === 5000 ){ // after 5 seconds has passed reset the timer and stop the looper
                console.log(looper);
                timer = 0;
                clearInterval(looper); // stop the wheel spinning
            }


    }
    document.getElementById('spinButton').addEventListener("click", event => {
        const speed = 100;
        startWheelAnimation("wheel", speed);
    });
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You should not create a new setTimerInterval in each execution of the function. This will accumulate different active intervals, and you'll only have the reference to the last one you created.

Instead move that piece of code out of the function, and place it in the event handler you have as addEventListener call back:

document.getElementById('spinButton').addEventListener("click", event => {
    const speed = 100;
    const elementid = "wheel";
    // schedule the repeated run:
    looper = setInterval( ()=>{
        // at the rate of speed var run the following code
        startWheelAnimation(elementid, speed );
    }, 
    speed);
    // also run it immediately
    startWheelAnimation(elementid, speed);
});
about 4 years ago · Juan Pablo Isaza Relatório

0

After each iteration - startWheelAnimation call, you create a new setInterval instance recursively (!) and assign it to looper. Therefore clearInterval only clears the most recent instance.

One fix would be to check if degrees or timer are set to their starting value:

if (degrees == 0 || timer == 0) {
    looper = setInterval( ()=>{
        // at the rate of speed var run the following code
        startWheelAnimation( elementId, speed );
    }, 
    speed);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda