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.
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.
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.
The clearInterval() method clears a timer set with the setInterval() method.
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'.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With