How to wait 5 seconds with jQuery?

Jquery

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

Built in javascript http://www.w3schools.com/js/js_timing.asp">setTimeout</a>;.

setTimeout(
  function() 
  {
    //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. http://api.jquery.com/delay/">Check it out. Note that .delay only works with the jQuery effects queues.

Solution 2 - Jquery

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);

Solution 3 - Jquery

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();

Solution 4 - Jquery

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.

Solution 5 - Jquery

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();
  });
}

Solution 6 - Jquery

The Underscore library also provides a "delay" function:

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

Solution 7 - Jquery

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:

$('') .delay(100 /ms/) .queue( (next) => { $('#result').text('done.'); next(); } );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

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

// add wait as $.wait() standalone and $(elem).wait() for animation chaining
(function($) {

  $.wait = function(duration, completeCallback, target) {
    $target = $(target || '<queue />');
    return $target.delay(duration).queue(function(next){completeCallback && completeCallback.call($target); next();});
  }

  $.fn.wait = function(duration, completeCallback) {
    return $.wait.call(this, duration, completeCallback, this);
  };

})(jQuery);

//TEST
$(function() {

  // stand alone
  $.wait(1000, function() {
    $('#result')
    .append('...done');
  });

  // chained
  $('#result')
  .append('go...')
  .wait('slow', function() {
    $(this).append('after slow');
  })
  .css({color: 'green'});
  
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

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

Solution 8 - Jquery

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);

Solution 9 - Jquery

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

Solution 10 - Jquery

For a quick and easy delay using aynsc/await you can do:

await $(window).delay(5000).promise();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrewView Question on Stackoverflow
Solution 1 - JqueryAlex BagnoliniView Answer on Stackoverflow
Solution 2 - JqueryDoug NeinerView Answer on Stackoverflow
Solution 3 - JqueryIan ClarkView Answer on Stackoverflow
Solution 4 - JquerymaudulusView Answer on Stackoverflow
Solution 5 - JqueryJo HasenauView Answer on Stackoverflow
Solution 6 - JqueryizilottiView Answer on Stackoverflow
Solution 7 - JqueryBananaAcidView Answer on Stackoverflow
Solution 8 - JquerydesbestView Answer on Stackoverflow
Solution 9 - JquerymakView Answer on Stackoverflow
Solution 10 - JqueryHenry HowesonView Answer on Stackoverflow