6

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
2
  • 1
    The last line setInterval(timer); makes no sense and gives an error, since timer variable is undefined. Commented Jun 20, 2012 at 15:50
  • the setInterval sets the whole engine running, without it, the code will STOP. It seems most of you here do NOT understand the difference between setInterval and setTimeout. Read your docs again. Commented Jun 20, 2012 at 16:07

1 Answer 1

13

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
Sign up to request clarification or add additional context in comments.

6 Comments

you were referencing the wrong object to kill, should be setInterval, not setTimeout
Why are people voting for an erroneous answer like this?
@DexterHuinda It should be clearTimeout(t), not clearInterval(t) - the interval code is incorrect and irrelevant.
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?
@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
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.