[jquery] wait() or sleep() function 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?

This question is related to jquery

The answer is


You can use the .delay() function.
This is what you're after:

.addClass("load").delay(2000).addClass("done");

xml4jQuery plugin gives sleep(ms,callback) method. Remaining chain would be executed after sleep period.

_x000D_
_x000D_
$(".toFill").html("Click here")
                .$on('click')
                .html('Loading...')
                .sleep(1000)
                .html( 'done')
                .toggleClass('clickable')
                .prepend('Still clickable <hr/>');
_x000D_
.toFill{border: dashed 2px palegreen; border-radius: 1em; display: inline-block;padding: 1em;}
        .clickable{ cursor: pointer; border-color: blue;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script type="text/javascript" src="https://cdn.xml4jquery.com/ajax/libs/xml4jquery/1.1.2/xml4jquery.js"></script>
        <div class="toFill clickable"></div>
_x000D_
_x000D_
_x000D_


I found a function called sleep function on the internet and don't know who made it. Here it is.

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

sleep(2000);

Realize that this is an old question, but I wrote 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(2000).addClass('done');

There is an function, but it's extra: http://docs.jquery.com/Cookbook/wait

This little 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);
    });
};

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

What if you want to wait before executing something outside of animation??

Use this:

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

What happens?: In this scenario it waits 600 miliseconds before executing the code specified within the curly braces.

This helped me a great deal once I figured it out and hope it will help you as well!

IMPORTANT NOTICE: 'window.setTimeout' happens asynchronously. Keep that in mind when writing your code!


That'd be .delay().

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

If you are doing AJAX stuff tho, you really shouldn't just auto write "done" you should really wait for a response and see if it's actually done.