117

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

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

Is there any way?

9 Answers 9

209

setTimeout will execute some code after a delay of some period of time (measured in milliseconds). However, an important note: because of the nature of javascript, the rest of the code continues to run after the timer is setup:

$('#someid').addClass("load");

setTimeout(function(){
  $('#someid').addClass("done");
}, 2000);

// Any code here will execute immediately after the 'load' class is added to the element.
2
  • 2
    this is a poor solution at present moment because it loses the advantage of having jquery control over the animation, like .stop(). a much better solution is .delay()
    – user151496
    May 11, 2015 at 16:22
  • 7
    @user123blahblah ... this is the PROPER solution for the question (which has nothing to do with animation). .delay does jack beans outside the animation queue. Whomever upvoted your erroneous comment, were mislead themselves. Mar 19, 2019 at 16:03
35

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.

2
  • 1
    Also Steven you want to .removeClass('load') otherwise your adding both classes load and done, which is probably undesired. If you are indeed waiting for an asynchronous action to complete, your best bet is to do .addClass WHEN it completes and is successful, if not .addClass('error') maybe an idea
    – Gary Green
    Apr 19, 2011 at 21:41
  • 55
    The jQUery "delay()" function in no way provides anything like a general-purpose "wait" facility. It's a part of the animation system, and only applies to the animation queue. The function always returns immediately, and execution continues without pause.
    – Pointy
    Apr 19, 2011 at 21:53
27

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!

21

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

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);
    });
};
0
2

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

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

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

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

$(".toFill").html("Click here")
                .$on('click')
                .html('Loading...')
                .sleep(1000)
                .html( 'done')
                .toggleClass('clickable')
                .prepend('Still clickable <hr/>');
.toFill{border: dashed 2px palegreen; border-radius: 1em; display: inline-block;padding: 1em;}
        .clickable{ cursor: pointer; border-color: blue;}
<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>

0

I think I have something that can help you and that is working with deferred. Used with the $.when it pauses until the task is done and then continues: it searches for Deferred elements. You can also chain events, one after the other, waiting for the previous one to finish to continue with the next.

$.when( $('#element').addClass('load'), $('#element').addClass('done') ).then(function(x) { console.info('Already done') });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.