JavaScript
x
15
15
1
var a = 0;
2
3
window.addEventListener("keydown", function(e) {
4
5
clearInterval(interval) //this dont work
6
var interval = setInterval(function() { //this is good
7
if (a == 0) {
8
console.log(a);
9
a = 10;
10
} else if (a == 10) {
11
console.log(a);
12
}
13
}, 120)
14
})
15
//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 needclearInterval
for that.