3

Can I do this using jQuery or should I be looking at using something else?

Kev
  • 118,037
  • 53
  • 300
  • 385
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

4 Answers4

17

The jQuery.delay() function is designed to delay execution of functions in the jQuery queue. There is already a built-in Javascript function for handling interval functionality, you wouldn't use jQuery to achieve that.

setInterval(function() {
    alert("Message to alert every 5 seconds");
}, 5000);
Highway of Life
  • 22,803
  • 16
  • 52
  • 80
2

Again, no need for jQuery here:

setInterval(function() { 
   alert("How Now Brown Cow");
}, 5000);

(Don't tell anyone, but @Justin Niessner is right, jQuery is JavaScript)

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
1

You can either use setInterval() or setTimeout(). There may be a jQuery specific helper function as well.

setInterval() takes 2 parameters - a function to execute, and the delay in milliseconds between calls. It will keep calling the function until you change or pages or call clearInterval(intervalID). You have to pass in the value returned by setInterval() to clear it.

setTimeout() takes the same parameters, but it will only execute once. You can get around that by having the last line in the function you pass to setTimeout() call setTimeout() again.

I've noticed that in some browsers, you're restricted in what you can do with setInterval() - for instance, it might not let you call setInterval() on page load.

Sam Dufel
  • 17,560
  • 3
  • 48
  • 51
0

I use this script Cookbook/wait with a small plugin and it works pretty well:

(function($){

   $.fn.runItIf = function(ex, fn, args) {

      var self = this;

      return $(self).queue(function() {

          args = args || [];
          if (ex)
             fn.apply.(self, args );

          $(self).dequeue();
      });
   };

   $.fn.runIt = function(fn, args) {

     return $(this).runItIf(true, fn, args);

   };

   $.fn.wait = function(time, type) {

        time = time || 1000;
        type = type || "fx";

        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                $(self).dequeue();
            }, time);
        });
    };

})(jQuery); 

Example based on the example in Cookbook/wait:

   function runIt() {

      var expression = true;

      $("div").wait()
              .animate({left:'+=200'},2000)
              .runIt(function() { /* ... */ } ).wait(10)
              .runItIf(expression, function() { /* ... */ } ).wait(10)
              .animate({left:'-=200'},1500,runIt);
   }
   runIt();
andres descalzo
  • 14,887
  • 13
  • 64
  • 115