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 intervalinside your function so it gets reset every time the function runs. setTimeoutwill call a function, once, after a time period. It won’t clear an interval, you needclearIntervalfor that.