Home > database >  clearInterval is not working on keydown addEventListener inside setInterval in javascript
clearInterval is not working on keydown addEventListener inside setInterval in javascript

Time:10-10

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)
 }
})

CodePudding user response:

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.

CodePudding user response:

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);
  }
});

CodePudding user response:

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)
 }
})
  • Related