开发者

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.

开发者_Go百科

How can I achieve this?


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.


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


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


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.


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


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.


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


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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜