Skip to content

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) {
      a = 10;
    } else if (a == 10) {
  }, 120)

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


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.