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.

isognomon
  • 75
  • 1
  • 1
  • 7
  • 1
    The last line `setInterval(timer);` makes no sense and gives an error, since `timer` variable is undefined. – VisioN Jun 20 '12 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. – Dexter Huinda Jun 20 '12 at 16:07

1 Answers1

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);
});
Chris Sobolewski
  • 12,819
  • 12
  • 63
  • 96
  • you were referencing the wrong object to kill, should be `setInterval`, not `setTimeout` – Dexter Huinda Jun 20 '12 at 15:53
  • Why are people voting for an erroneous answer like this? – Dexter Huinda Jun 20 '12 at 15:59
  • @DexterHuinda It should be `clearTimeout(t)`, not `clearInterval(t)` - the interval code is incorrect and irrelevant. – Anthony Grist Jun 20 '12 at 15:59
  • 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? – Dexter Huinda Jun 20 '12 at 16:04
  • @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](http://jsfiddle.net/anthonygrist/7Sv8B/) – Anthony Grist Jun 20 '12 at 17:08
  • I copied and pasted the original code, as I gave the asker the benefit of the doubt... Guess I shouldn't have done that... – Chris Sobolewski Jun 20 '12 at 17:17