Steven Moss
Steven Moss

Reputation: 1257

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?

Upvotes: 118

Views: 617075

Answers (9)

LeoBeltranV
LeoBeltranV

Reputation: 1

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

Upvotes: 0

Maytha8
Maytha8

Reputation: 866

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

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

Upvotes: 1

desbest
desbest

Reputation: 4896

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

Upvotes: 2

J. Louw
J. Louw

Reputation: 265

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!

Upvotes: 27

Sasha Firsov
Sasha Firsov

Reputation: 697

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>

Upvotes: 0

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

Upvotes: 2

madlee
madlee

Reputation: 647

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

Upvotes: 21

Chris Cherry
Chris Cherry

Reputation: 28554

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.

Upvotes: 211

Oscar Godson
Oscar Godson

Reputation: 32726

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.

Upvotes: 35

Related Questions