How to stop a timer function from running?
Asked Answered
M

1

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.

Macintyre answered 20/6, 2012 at 15:46 Comment(2)
The last line setInterval(timer); makes no sense and gives an error, since timer variable is undefined.Warga
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.Queenqueena
S
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);
});
Swinger answered 20/6, 2012 at 15:48 Comment(6)
you were referencing the wrong object to kill, should be setInterval, not setTimeoutQueenqueena
Why are people voting for an erroneous answer like this?Queenqueena
@DexterHuinda It should be clearTimeout(t), not clearInterval(t) - the interval code is incorrect and irrelevant.Cat
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?Queenqueena
@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 jsFiddleCat
I copied and pasted the original code, as I gave the asker the benefit of the doubt... Guess I shouldn't have done that...Swinger

© 2022 - 2024 — McMap. All rights reserved.