Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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?
by

2 Answers

akshay1995
The Underscore library also provides a "delay" function:

_.delay(function(msg) { console.log(msg); }, 5000, 'Hello');
pankajshivnani123
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();

Login / Signup to Answer the Question.