0

Possible Duplicate:
How to clearInterval with unknown ID?

I currently start a series of setIntervals(function(), time) outside of functions in the part of my page header.

I now need the abliity to stop and start these global setIntervals from within a function. There is lots of questions doing this with user input but I need the script to do it automatically. Essentially when the initially setInterval function fires it will disable future firings until the user acknowledges it.

What's the best way to do this.

Jquery is acceptable, or even preffered.

Community
  • 1
  • 1
Flatlyn
  • 2,040
  • 6
  • 40
  • 69
  • Please post the code you have – Rory McCrossan Nov 14 '12 at 11:53
  • I'm pretty sure if you thoroughly read the other questions/answers that already exist on this topic, you can figure it out. There is no big difference in stopping `setInterval` on button click or "automatically" in both cases you eventually call the same function (`clearInterval`). – Felix Kling Nov 14 '12 at 11:55
  • [This answer](http://stackoverflow.com/a/7663883/447356) looks most suitable for what you need. – Shadow The GPT Wizard Nov 14 '12 at 12:01

3 Answers3

2

You'll have to asign the interval to a variable, then use the function clearInterval to stop it. https://developer.mozilla.org/en-US/docs/DOM/window.clearInterval

var interval = setInterval(function(), time)
clearInterval(interval)
roacher
  • 666
  • 3
  • 8
1

I use something like this :

var timers = [];

var timer = function (code, delay) {

   var id = "timer" + timers.length;

    timers.push({ id : id, ref : setInterval(code, delay)});
}

new timer(function(e) { alert("I'm first timer!");}, 1000);                 

​
loxxy
  • 12,990
  • 2
  • 25
  • 56
0
<input type="button" value="click me" onClick="disableInterval()"/>

<script type="text/javascript">
    $(document).ready(function () {
       var  intervalID = setInterval(yourFunction(), time);
  });
disableInterval = function(){   
 window.clearInterval(intervalID);
}
</script>