5

I'm trying to get a function to repeat itself once it starts, but I must be off today because I can't figure it out. Here's my code:

function runNext() {
    galleryNext().delay(1500).runNext();
}

Thanks in advance.

CoreyRS
  • 2,227
  • 3
  • 26
  • 44
  • 5
    I would recommend using javascript's `setTimeout` or `setInterval` to call a function repeatedly – MrOBrian Jul 23 '12 at 17:50
  • 1
    This will not work unless function runNext is a method of the object returned by delay. – Austin Jul 23 '12 at 17:50
  • `.delay()` is used for animations in the queue, I see no animations in your code, thus no queue exists to delay - stuff like `.slideUp()` for instance – Mark Schultheiss Jul 23 '12 at 17:53

2 Answers2

18

If you want to call a function on a regular interval you should use setInterval().

var myFunction = function() {};
setInterval(myFunction, 1000); // call every 1000 milliseconds

If you ever need to stop the function from being called forever, setInterval() returns an id that you can use to stop the timer as well. Here's an example.

var myFunction = function() {};
var timer = setInterval(myFunction, 1000);
clearTimeout(timer);
jessegavin
  • 74,067
  • 28
  • 136
  • 164
  • aha, stopping the function was going to be my next question. nice one. – CoreyRS Jul 23 '12 at 18:06
  • The clearing of the interval should be done using `clearInterval(timer); `and not `clearTimeout(timer);` as timer is an interval. Although it is very likely this will work, if at any point the method to clearing an interval changes, the code above will not work: http://stackoverflow.com/questions/9913719/are-cleartimeout-and-clearinterval-the-same – ctwheels Dec 18 '15 at 17:26
2

You can't attach a user defied function like a DOM method. jQuery chaining applies to DOM manipulation and animations, because each process returns the DOM node in question. Plus delay just delays an animation, what you want here is to run a function after some time constantly, so use setTimeout:

(function foo() {
  setTimeout(function() { foo() },1000);
  })();
SexyBeast
  • 7,913
  • 28
  • 108
  • 196