Reputation: 1333
Relative newcomer to JS, trying to wrap my head around the scheduling. This code will start the appending but not stop it. I'm pretty sure that the problem is that 'clearInterval' needs to address a variable which has been assigned a 'setInterval' function. What I can't seem to grasp is how to properly phrase that.
var hmm = function appendStuff(){
$("p").append("<b>Appended text</b>");
};
$("#start").click(function() {
console.log("startClicked"); // working...
window.setInterval(hmm, 1000) // working...
});
$("#stop").click(function() {
console.log("stopClicked"); // working...
window.clearInterval(hmm)
});
Thanks!
Upvotes: 1
Views: 3382
Reputation: 691
The setInterval()
function returns an ID. This is what you want to assign to hmm
.
Also, the first parameter of setInterval()
is the function you want to call every interval.
var hmm = null;
function appendStuff(){
$("p").append("<b>Appended text</b>");
};
$("#start").click(function() {
console.log("startClicked"); // working...
hmm = window.setInterval(appendStuff, 1000) // working...
});
$("#stop").click(function() {
console.log("stopClicked"); // working...
window.clearInterval(hmm)
});
Upvotes: 2
Reputation: 1678
You can use this setInterval() example from w3School here. Basically you use syntax like for example:
var yourIntervalVariable = setInterval(function(){
// do something here..
}, 1000);
And then you can use clearInterval() on the variable like this:
clearInterval(yourIntervalVariable);
Upvotes: 0
Reputation: 1108
You need to assign the setInterval object to a variable and pass it to clearInterval, not the funciton variable of SetInterval into clearInterval. Refer here.
var hmm = function appendStuff(){
$("p").append("<b>Appended text</b>");
};
var interval;
$("#start").click(function() {
console.log("startClicked"); // working...
interval = window.setInterval(hmm, 1000) // working...
});
$("#stop").click(function() {
console.log("stopClicked"); // working...
window.clearInterval(interval)
});
Upvotes: 1