function consoleTest() {
setInterval(function(){
console.log('Hello World');
}, 1000);
}
$('#button').on('click', function(){
clearInterval(consoleTest);
});
consoleTest();
I created a simple app when I click the button it will stop/pause the interval. I know how to make it work I just need to declare a variable outside the function and contain there the setInterval, now I am just confused why clearInterval won't work if I call it via a function, somebody please explain it to me.
This is the correct usage of setInterval
and cleaInterval
.
setInterval
returnes a value which you need to keep in a variable scoped for both function. When you want to clear the interval, use clearInterval
and pass it the variable as a parameter:
var interval;
function consoleTest() {
interval = setInterval(function() {
console.log('Hello World');
}, 1000);
}
$('#button').on('click', function() {
clearInterval(interval);
});
consoleTest();
For further reading: clearInterval and setInterval.
There's two issues here. Firstly you don't set the returned timer id from setInterval()
anywhere. consoleTest
is the function that wraps the timer, not a reference to the timer, which is what should be given to clearInterval()
. Secondly, you need that timer reference to be in scope of both functions. With that in mind, try this:
function consoleTest() {
return setInterval(function(){
console.log('Hello World');
}, 1000);
}
$('#button').on('click', function(){
clearInterval(interval);
});
var interval = consoleTest();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With