Skip to content
Advertisement

javascript clearInterval() function is not working

   var a = 0;

window.addEventListener("keydown", function(e) {
 
  clearInterval(interval) //this dont work
  var interval = setInterval(function() { //this is good
    if (a == 0) {
      console.log(a);
      a = 10;
    } else if (a == 10) {
      console.log(a);
    }
  }, 120)
})

//I want when user press key interval stop , than new interval start again but old interval cant stop

Advertisement

Answer

You have two problems.

  • You have var interval inside your function so it gets reset every time the function runs.
  • setTimeout will call a function, once, after a time period. It won’t clear an interval, you need clearInterval for that.
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement