Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a timer function from running?

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.

like image 752
isognomon Avatar asked Jun 20 '12 15:06

isognomon


People also ask

How do you stop a timer in Matlab?

stop( t ) stops the timer object t . If t is an array of timer objects, stop stops each timer. The stop function sets the Running property of the timer object to 'off' and executes the StopFcn callback.

What is timer function in JavaScript?

In JavaScript, a timer is created to execute a task or any function at a particular time. Basically, the timer is used to delay the execution of the program or to execute the JavaScript code in a regular time interval. With the help of timer, we can delay the execution of the code.

How do you stop a timer in HTML?

The clearInterval() method clears a timer set with the setInterval() method.

How do you end a timer in JavaScript?

Clicking the Stop button clears the timer by using the clearInterval(), passing in the 'check' variable that is returned by the call to setInterval(). The last step is to reset the value of the counter to '0'.


1 Answers

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);
});
like image 133
Chris Sobolewski Avatar answered Sep 26 '22 17:09

Chris Sobolewski