475

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?

Andrew
  • 227,796
  • 193
  • 515
  • 708

10 Answers10

871

Built in javascript setTimeout.

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. Check it out. Note that .delay only works with the jQuery effects queues.

CarlosAS
  • 654
  • 2
  • 10
  • 31
Alex Bagnolini
  • 21,990
  • 3
  • 41
  • 41
  • 2
    is there anything in jQuery that you can use instead of using setTimeout? – Andrew Dec 02 '09 at 22:06
  • 39
    jQuery is written in javascript. If you include and use jQuery, you need javascript. If you have javascript, you have `setTimeout`. – Alex Bagnolini Dec 02 '09 at 22:08
  • 5
    Yeah, I know. I mean that $('.message').wait(5000).slideUp(); would be so much nicer. but I don't think a wait() function exists. – Andrew Dec 02 '09 at 22:10
  • Yeah, definitely do it with .delay(timeInMS). We <3 jquery! – nasty pasty Aug 02 '11 at 09:02
  • 70
    Just a sidenote - .delay only works with the jQuery effects queues, so it's perfect for slides and fades like this. It just took me a while to realize that it doesn't work for other things that you can do with jQuery. – Joel Beckham May 21 '12 at 03:52
  • as pointed out by @JoelBeckham, and [the jQuery's delay() page](https://api.jquery.com/delay/) "The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases" – Adriano Mar 05 '14 at 17:59
  • Well - you can add anything you like to the queue, so delay will work for any other function as well. – Jo Hasenau Mar 25 '14 at 11:16
  • `delay` in my case didn't worked consistently, but `setTimeout` did. Below is my code using `delay` which was supposed to execute on click of a button and it did worked, but only once. Repeated clicks on source button didn't executed the queued function: `dropdownObj.trigger('change').delay(100).queue(function() { selectOptionValueInDropdown(value, anotherDropdownObj); });` – Jignesh Gohel Aug 24 '15 at 11:21
74

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);
Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
53

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();
Ian Clark
  • 9,237
  • 4
  • 32
  • 49
44
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.

maudulus
  • 10,627
  • 10
  • 78
  • 117
27

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();
  });
}
Jo Hasenau
  • 2,526
  • 1
  • 14
  • 16
9

The Underscore library also provides a "delay" function:

_.delay(function(msg) { console.log(msg); }, 5000, 'Hello');
izilotti
  • 4,757
  • 1
  • 48
  • 55
9

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:

$('<queue/>')
.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.

BananaAcid
  • 3,221
  • 35
  • 38
4

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);
desbest
  • 4,746
  • 11
  • 51
  • 84
2
$( "#foo" ).slideUp( 300 ).delay( 5000 ).fadeIn( 400 );
mehmetakkus
  • 631
  • 1
  • 8
  • 25
1

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

await $(window).delay(5000).promise();
Henry Howeson
  • 677
  • 8
  • 18