How to Wait or Delay Script in jQuery

June 17, 2014 Development, jQuery

How to Wait or Delay Script in jQuery

Continuing yesterday’s post involving setTimeout(), I wanted to expand on the useful function and other ways to wait in jQuery.

The basic usage of setTimeout() is to execute code inside the function after a certain number of milliseconds. Just like most javascript and jQuery functions, time is counted in very small units.

setTimeout(
  function() 
  {
    // Execute code here
    $('.item').fadeIn('250');
  }, 5000); // Wait 5 seconds or 5,000 milliseconds

If you would like to cancel this operation, you can declare it as a variable. For more information on how to do this, please read the blog post Easily Cancel setTimeout() Function Through Variable.

Starting with jQuery v1.4, the delay() function was introduced. It’s official description is “Set a timer to delay execution of subsequent items in the queue.” This differs from the setTimeout() function demonstrated above in that the items have to be listed in a row. In a sense, the items have to be chained together.

$('.item').fadeIn('250').delay('250').fadeOut('250');

There is also the doTimeout jQuery plugin by Ben Alman. He describes the improved function as the following: “Just think of setTimeout, but with additional management options, jQuery chainable, and with a simpler and more flexible API.”

$.doTimeout(5000, function()
{
	// Execute code here
    $('.item').fadeIn('250');
});

Ben also has lots of examples on the plugin page which is great to see. I can’t begin to count how many plugins I’ve used that have barely any documentation and a single example with basic options.

Back on topic, I would suggest setTimeout() or delay() for most situations but doTimeout seems to have a lot of advantages for more complicated matters.

Let's Talk About Your New Website

View Portfolio Contact Today