Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

179
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda