[jquery] 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?

This question is related to jquery

The answer is


Use a normal javascript timer:

$(function(){
   function show_popup(){
      $("#message").slideUp();
   };
   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:

$(window).load(function(){
   function show_popup(){
      $("#message").slideUp();
   };
   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);

$( "#foo" ).slideUp( 300 ).delay( 5000 ).fadeIn( 400 );

Based on Joey's answer, I came up with an intended (by jQuery, read about 'queue') solution.

It somewhat follows the jQuery.animate() syntax - allows to be chained with other fx functions, supports 'slow' and other jQuery.fx.speeds as well as being fully jQuery. And will be handled the same way as animations, if you stop those.

jsFiddle test ground with more usages (like showing off .stop()), can be found here.

the core of the solution is:

_x000D_
_x000D_
$('<queue/>')_x000D_
.delay(100 /*ms*/)_x000D_
.queue( (next) => { $('#result').text('done.'); next(); } );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

the whole as a plugin, supporting usage of $.wait() and $(..).wait() :

_x000D_
_x000D_
// add wait as $.wait() standalone and $(elem).wait() for animation chaining_x000D_
(function($) {_x000D_
_x000D_
  $.wait = function(duration, completeCallback, target) {_x000D_
    $target = $(target || '<queue />');_x000D_
    return $target.delay(duration).queue(function(next){completeCallback && completeCallback.call($target); next();});_x000D_
  }_x000D_
_x000D_
  $.fn.wait = function(duration, completeCallback) {_x000D_
    return $.wait.call(this, duration, completeCallback, this);_x000D_
  };_x000D_
_x000D_
})(jQuery);_x000D_
_x000D_
//TEST_x000D_
$(function() {_x000D_
_x000D_
  // stand alone_x000D_
  $.wait(1000, function() {_x000D_
    $('#result')_x000D_
    .append('...done');_x000D_
  });_x000D_
_x000D_
  // chained_x000D_
  $('#result')_x000D_
  .append('go...')_x000D_
  .wait('slow', function() {_x000D_
    $(this).append('after slow');_x000D_
  })_x000D_
  .css({color: 'green'});_x000D_
  _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

Note: since wait adds to the animation stack, $.css() is executed immediately - as it is supposed: expected jQuery behaviour.


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:

$.wait(5000).then(disco);

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:

$(".my-element").delay(5000).fadeIn();

I realize that this is an old question, but here's a plugin to address this issue that someone might find useful.

https://github.com/madbook/jquery.wait

lets you do this:

$('#myElement').addClass('load').wait(5000).addClass('done');

The reason why you should use .wait instead of .delay is because not all jquery functions are supported by .delay and that .delay only works with animation functions. For example delay does not support .addClass and .removeClass

Or you can use this function instead.

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

sleep(5000);

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() {
    $(this).click().dequeue();
  });
}

The Underscore library also provides a "delay" function:

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

setTimeout(function(){


},5000); 

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

etc.