I'm a bit new to js and have been trying to figure out how to stop this function from running when I click on a button. I tried using clearInterval but I am not sure I am doing it properly. Can someone take a look at this code and point me in the right direction?
Code:
<div><h1 id="target"></h1></div>
<button id="stop">Stop</button>
Script:
var arr = [ "one", "two", "three"];
(function timer(counter) {
var text = arr[counter];
$('#target').fadeOut(500, function(){
$("#target").empty().append(text).fadeIn(500);
});
delete arr[counter];
arr.push(text);
setTimeout(function() {
timer(counter + 1);
}, 3000);
$("#stop").click(function () {
clearInterval(timer);
});
})(0);
setInterval(timer);
JS Fiddle: http://jsfiddle.net/58Jv5/13/
Thanks in advance for your help.
asked Jun 20, 2012 at 15:46
isognomon
751 gold badge1 silver badge7 bronze badges
1 Answer 1
You need to give JavaScript a reference to the interval:
var t = setTimeout(function() {
timer(counter + 1);
}, 3000);
Then you can clear it like so:
$("#stop").click(function () {
clearTimeout(t);
});
answered Jun 20, 2012 at 15:48
Chris Sobolewski
13k13 gold badges65 silver badges97 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
Dexter Huinda
you were referencing the wrong object to kill, should be
setInterval, not setTimeoutDexter Huinda
Why are people voting for an erroneous answer like this?
Anthony Grist
@DexterHuinda It should be
clearTimeout(t), not clearInterval(t) - the interval code is incorrect and irrelevant.Dexter Huinda
Did you read up to the rest of his code where it says :
setInterval(timer); ? This code sets the pace and gets the whole thing running, in an interval defined by timer. Stopping setInterval will stop the loop, not the setTimeout. See the difference?Anthony Grist
@DexterHuinda It does no such thing.
timer is a recursive function, that sets a timeout which calls itself (with an increased counter) when the timeout ends. It's also automatically called with a starting value of 0. The setInterval(timer) is unnecessary and incorrect, and will throw an error (see VisioN's comment on the question). Don't believe me? Have a jsFiddle |
lang-js
setInterval(timer);makes no sense and gives an error, sincetimervariable is undefined.