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

168
Visualizações
How can I cancel setInterval running with global variable?

I am trying to clear/stop setInterval from running, and have made changes to my approach based on other questions/answers I've found, but still can't get setInterval to stop running.

What I have here, is a Mutation Observer which detects a class change, and when that occurs, if two conditions are true (the presence of other classes), then some cursor tracking executes. All this works great.

When one of the two classes, .run-preview, is removed I then want to stop setInterval from running, as seen in the else if. I also have a commented line there where I was verifying that the else if is working, and it is.

I have a global variable intervalCursor = setInterval(move,1000/60);, and then am using that variable to later clearInterval(intervalCursor);.

const runPreview = document.querySelector('.projects');

new MutationObserver((mutations) => {
  if (mutations[0].attributeName === 'class') {
    console.log('Project list class changed');
 
    if ($('html').hasClass('no-touchevents') && ($('.projects').hasClass('run-preview'))) {
    
        var mouseX=window.innerWidth/2,
            mouseY=window.innerHeight/2;
        var intervalCursor = setInterval(move,1000/60);
            
        var projectPreview = {
         el:$('.image-container'),
         x:window.innerWidth/2, 
         y:window.innerHeight/2, 
         w:300,
         h:300, 
         update:function() {
           l = this.x-this.w/2; 
           t = this.y-this.h/2; 
           this.el.css({ 
            'transform':
            'translate3d('+l+'px,'+t+'px, 0)' });
            //console.log("transform");
           }
        }
        
        $(window).mousemove (function(e){
          mouseX = e.clientX;
          mouseY = e.clientY;
          //console.log("mousemove");
        })
        
        
        function move(){
          projectPreview.x = lerp (projectPreview.x, mouseX, 0.1);
          projectPreview.y = lerp (projectPreview.y, mouseY, 0.1);
          projectPreview.update() 
          console.log("move");
        }
        
        function lerp (start, end, amt){
          return (1-amt)*start+amt*end
        }

    } else if (!$('.projects').hasClass('run-preview')) {
        clearInterval(intervalCursor);
        return;
        //$('#content-container').addClass('test');
    }
 
  }
})

.observe(runPreview, { attributes: true });

Am I doing something wrong?

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Thanks to Ouroborus, I was able to solve this by creating the variable separately from the MutationObserver, and then using it to run setInterval(move,1000/60); later. Thus allowing setInterval to be cleared/stopped when I need to.

var intervalCursor

const runPreview = document.querySelector('.projects');

new MutationObserver((mutations) => {
  if (mutations[0].attributeName === 'class') {
    console.log('Project list class changed');
 
    if ($('html').hasClass('no-touchevents') && ($('.projects').hasClass('run-preview'))) {
    
        var mouseX=window.innerWidth/2,
            mouseY=window.innerHeight/2;
            
        var projectPreview = {
         el:$('.image-container'),
         x:window.innerWidth/2, 
         y:window.innerHeight/2, 
         w:300,
         h:300, 
         update:function() {
           l = this.x-this.w/2; 
           t = this.y-this.h/2; 
           this.el.css({ 
            'transform':
            'translate3d('+l+'px,'+t+'px, 0)' });
            //console.log("transform");
           }
        }
        
        $(window).mousemove (function(e){
          mouseX = e.clientX;
          mouseY = e.clientY;
          //console.log("mousemove");
        })
        
        
        intervalCursor = setInterval(move,1000/60);
        function move(){
          projectPreview.x = lerp (projectPreview.x, mouseX, 0.1);
          projectPreview.y = lerp (projectPreview.y, mouseY, 0.1);
          projectPreview.update() 
          console.log("move");
        }
        
        function lerp (start, end, amt){
          return (1-amt)*start+amt*end
        }

    } else if (!$('.projects').hasClass('run-preview')) {
        clearInterval(intervalCursor);
        //$('#content-container').addClass('test');
    }
 
  }
})

.observe(runPreview, { attributes: true });
about 4 years ago · Santiago Gelvez 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