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

178
Visualizações
clearInterval is not working on keydown addEventListener inside setInterval in javascript

This code will work fine when you press ArrowRight key in once at a time. But When you press ArrowKey twice or many at a time then the interval execute with infinity, clearInterval and if condition will not work. please help. Must run this code in your pc. then you will understand what I want to say.

var increaseNum;
function endLevel() {
   window.clearInterval(increaseNum);
}

var n=0;
window.addEventListener("keydown", (e)=>{
 if(e.key == "ArrowRight"){
   increaseNum = setInterval(()=>{
      n +=1;
      if(n>10){       
       endLevel();
      }
      console.log(n);
   }, 50)
 }
})

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

0

Can't you do this:

window.addEventListener("keydown", (e) => {
    if (e.key == "ArrowRight") {
        function endLevel() {
            window.clearInterval(increaseNum);
        }
        var increaseNum;
        var n = 0;
        increaseNum = setInterval(() => {
              n +=1;
              if(n>10){       
               endLevel();
              }
              console.log(n);
        }, 50)
    }
})

Because as you have it now, when you press multiple times increaseNum gets reassigned, hence clearInterval will not work as you expect. Also all those intervals will be increasing the same n.

In the above example, multiple intervals will fire now, each closing over its own version of n, increaseNum, endLevel. Not sure if that's what you want though.

Or you may find more suitable to not start a new interval if there is another already running. Or you may clear existing interval (as in the other answer). Depends on your use case.

about 4 years ago · Juan Pablo Isaza Relatório

0

you can just check if there is already a count in progress and if there is one don't start another, something like this:

var increaseNum;
function endLevel() {
  window.clearInterval(increaseNum);
  increaseNum = null;
  n = 0;
}

var n = 0;
window.addEventListener("keydown", (e) => {
  if (increaseNum) return;
  if (e.key == "ArrowRight") {
    increaseNum = setInterval(() => {
      n += 1;
      if (n > 10) {
        endLevel();
      }
      console.log(n);
    }, 50);
  }
});

about 4 years ago · Juan Pablo Isaza Relatório

0

If I understand what you are wanting to do as while the user is pressing the right arrow then you want the game to continue but if they stop then the setInterval will reach n>10 and the endLevel method will be called.

let increaseNum;
let n = 0;
let reset = true;
function endLevel() { 
    n = 0;
    window.clearInterval(increaseNum);
}

window.addEventListener("keydown",  (e)=>{
 if(e.key == "ArrowRight"){
   window.clearInterval(increaseNum);
   n = 0;

   increaseNum = setInterval(()=>{
      if(n>10){     
        endLevel();
      }
      n++;
   }, 50)
 }
})
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