How to wait 5 seconds with jQuery?


I'm trying to create an effect where the page loads, and after 5 seconds, the success message on the screen fades out, or slides up.

How can I achieve this?

4/15/2014 8:09:39 PM

Accepted Answer

Built in javascript setTimeout.

    //do something special
  }, 5000);

UPDATE: you want to wait since when the page has finished loading, so put that code inside your $(document).ready(...); script.

UPDATE 2: jquery 1.4.0 introduced the .delay method. Check it out. Note that .delay only works with the jQuery effects queues.

6/20/2017 7:50:24 AM

Use a normal javascript timer:

   function show_popup(){
   window.setTimeout( show_popup, 5000 ); // 5 seconds

This will wait 5 seconds after the DOM is ready. If you want to wait until the page is actually loaded you need to use this:

   function show_popup(){
   window.setTimeout( show_popup, 5000 ); // 5 seconds

EDIT: In answer to the OP's comment asking if there is a way to do it in jQuery and not use setTimeout the answer is no. But if you wanted to make it more "jQueryish" you could wrap it like this:

$.wait = function( callback, seconds){
   return window.setTimeout( callback, seconds * 1000 );

You could then call it like this:

$.wait( function(){ $("#message").slideUp() }, 5);

I ran across this question and I thought I'd provide an update on this topic. jQuery (v1.5+) includes a Deferred model, which (despite not adhering to the Promises/A spec until jQuery 3) is generally regarded as being a clearer way to approach many asynchronous problems. Implementing a $.wait() method using this approach is particularly readable I believe:

$.wait = function(ms) {
    var defer = $.Deferred();
    setTimeout(function() { defer.resolve(); }, ms);
    return defer;

And here's how you can use it:


However if, after pausing, you only wish to perform actions on a single jQuery selection, then you should be using jQuery's native .delay() which I believe also uses Deferred's under the hood:




Place your code inside of the { }

300 = 0.3 seconds

700 = 0.7 seconds

1000 = 1 second

2000= 2 seconds

2200 = 2.2 seconds

3500 = 3.5 seconds

10000 = 10 seconds



Have been using this one for a message overlay that can be closed immediately on click or it does an autoclose after 10 seconds.

button = $('.status-button a', whatever);
if(button.hasClass('close')) {
  button.delay(10000).queue(function() {

The Underscore library also provides a "delay" function:

_.delay(function(msg) { console.log(msg); }, 5000, 'Hello');

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]