Wait () or sleep () in jquery?

I want to add a class, wait 2 seconds and add another class.

.addClass("load").wait(2sec).addClass("done"); 

Is there any way?

+76
jquery
Apr 19 2018-11-21T00:
source share
6 answers

setTimeout will execute some code after a delay of a certain period of time (measured in milliseconds). However, it is important to note: due to the nature of javascript, the rest of the code continues to work after setting the timer:

 $('#someid').addClass("load"); setTimeout(function(){ $('#someid').addClass("done"); }, 2000); // Any code here will execute immediately after the 'load' class is added to the element. 
+139
Apr 19 2018-11-21T00:
source share

This will be .delay() .

http://api.jquery.com/delay/

If you are doing tho AJAX material, you really should not just write "done", you should really wait for an answer and see if it is really done.

+35
Apr 19 2018-11-21T00:
source share

Understand that this is an old question, but I wrote a plugin to solve this problem, which may be useful.

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

allows you to do this:

 $('#myElement').addClass('load').wait(2000).addClass('done'); 
+17
Nov 12
source share

delay () will not do the job. The delay () problem is part of the animation system and applies only to animation queues.

What if you want to wait until something is done outside the animation?

Use this:

 window.setTimeout(function(){ // do whatever you want to do }, 600); 

What happens ?: In this scenario, it waits 600 milliseconds before executing the code indicated in curly brackets.

It really helped me figure it out, and I hope it helps you!

+10
Mar 18 '16 at 9:55
source share

There is a function, but it is optional: http://docs.jquery.com/Cookbook/wait

This small snippet allows you to wait:

 $.fn.wait = function(time, type) { time = time || 1000; type = type || "fx"; return this.queue(type, function() { var self = this; setTimeout(function() { $(self).dequeue(); }, time); }); }; 
+2
Apr 19 2018-11-21T00:
source share

Using the setTimeout function, for example, Visit here, for example,

-one
Aug 23 '13 at 18:55
source share



All Articles