We keep up on the newest technologies and write about it every chance we can get. Feel free to browse.

jQuery Delay

Posted: August 4th, 2009 | Author: | Filed under: Coding | 2 Comments »

I often get asked about a delay in jQuery. Unfortunately, at the time of this writing, jQuery doesn’t have a delay function. However, this is a simple little clever workaround you can use. It involves using the “animate” function. You should recognize this as the function that simple animates something via element styles.

For example, If you have a div colored black and run .animate({background-color:#ffffff}, 2000) on it, in 2 seconds it will have faded to white. If you use this function to modify something to the same over the period of time, you effectively get delay. For example, why not use opacity?

$(document).ready(function() {
  $(".message").show("slow").animate({opacity: 1.0}, 4000).hide("slow");
});

Doing this would show a previously hidden div classed “message” for 4 seconds, and then hide it again. Play around with it to get the effect you want. You don’t have to use opacity either, its just not a commonly used CSS element.


2 Comments on “jQuery Delay”

  1. #1 chris brickhouse said at 8:48 pm on March 8th, 2010:

    or, you could just do window.setTimeout(function, delay)

  2. #2 Thomas Quick said at 2:58 pm on March 18th, 2010:

    I believe this would be a better approach – just as Chris Brickhouse alluded to.

    jQuery(function($) {
    $(“.message”).show(‘slow’, function() {
    setTimeout(function() {
    $(“.message”).hide(‘slow’);
    }, 4000);
    });
    });


Leave a Reply