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

321
Visualizações
Why clearinterval() does not stops the setInterval() in JS?

I need to start the setInterval When the particular id is 2 and to clear the Interval using clearInterval.

When I click on the button, the value in the button should be 0,1,2,3,0,1,2.... When the value is 2, it should display Date.now().


<button id="b1">0</button>
<button id="b2">0</button>
<button id="b3">0</button>

$("button").click(function () {
  buttonVal(this);
});

var v = [];

function buttonVal(ele) {
  v[ele.id] =
    typeof v[ele.id] === "undefined" ? 0 : v[ele.id] === 3 ? 0 : v[ele.id] + 1;
  switch (v[ele.id]) {
    case 0:
      break;
    case 1:
      document.getElementById(ele.id).innerHTML = v[ele.id];
      break;

    case 2:
      document.getElementById(ele.id).innerHTML = v[ele.id];
      break;

    case 3:
      document.getElementById(ele.id).innerHTML = v[ele.id];
      break;

    default:
      document.getElementById(ele.id).innerHTML = 6;
      break;
  }
 if(v[ele.id] == 2) {
   
   var refreshId = setInterval(function(){
     v[ele.id] = {'refreshId': refreshId};
     document.getElementById(ele.id).innerHTML = Date.now();
    }, 2000);
   }
  else {
    clearInterval(refreshId);
  }
}

The problem is clearInterval() is not working, When the button value is 2, it starts the setInterval()but it doesn't stops when the value is not 2. It just continues to run for all the button Values.

The button value runs like the below after clicking them 0,1,2,3, object1, object11, object111. Not sure, why the order is like the above.

Could anyone please help to stop the timer for the values other than 2.

Many thanks.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are defining var refreshId inside the if block, and trying to clear it in else, so the scope isn't the same. Your refreshId is a local variable.

Try defining it first outside the if block, or rather outside of the function itself.

var refreshId = null;

if(v[ele.id] == 2) {
 refreshId = setInterval(...)
 ...
else {
 clearInterval(refreshId);
}


about 4 years ago · Juan Pablo Isaza Relatório

0

When running a function all variables get redeclared again, this means when you say: var intervalId = interval(...). You create a new variable instead of saving it for later.

To solve this problem save the interval globally like shown below:

let interval;

function buttonVal(ele) {
 // code...
 
 if(v[ele.id] == 2) {
   interval = setInterval(function(){
     v[ele.id] = {'refreshId': refreshId};
     document.getElementById(ele.id).innerHTML = Date.now();
    }, 2000);
   }
  else {
    if (interval) {
      clearInterval(refreshId);
    }
  }
}

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