JQuery Function Scheduling Functions
I'm trying to achieve this with jQuery + JavaScript:
I have commands / functions that need to be called in sequence, with a little delay in between. Examples include changing an element's css property to show hiding another, etc.
JavaScript has no sleep function as far as I know. So I'm wondering if jQuery has a plugin or something that supports this feature?
Basically, a feature like $(window).schedule(function() { /* do something here*/ }, 500);
, would be nice. This will call the function into the queue and will be executed as soon as all previous functions in the queue have been executed, if there are no functions in the queue it will be executed immediately The integer parameter specifies the delay between this function and the previous one.
I think I know how to do this from scratch, but I hope there is a plugin for that, because it saves me from rethinking the wheel.
If not, I'll create this and let go. :)
source to share
I am not aware of a specific plugin that already exists (although I would be surprised if it did not exist). But if you just want a shared queue that isn't tied to any particular element, it's easy enough to get by without jQuery, perhaps something like this:
function Scheduler() {
var queue = [],
timer,
next = function () {
var item = queue.shift();
if (item) {
timer = setTimeout(function () {
item.cb.call(item.thisObj);
timer = null;
next();
}, item.delay);
}
};
this.schedule = function (delay, cb, thisObj) {
queue.push({
cb: cb,
delay: delay,
thisObj: thisObj
});
if (!timer) next();
return this;
};
}
var scheduler = new Scheduler();
scheduler.schedule(2000, function () {
$("h1").css("color", "red");
});
scheduler.schedule(500, someFunc)
.schedule(3000, someOtherFunc)
.schedule(1500, anotherFunc);
The main method .schedule()
returns an instance of the scheduler, so you can redirect duplicate calls as shown. And you can (optionally) pass the context to the callback function as shown in the following demo: http://jsfiddle.net/euggc0r2/1/
source to share
Use the jQuery, built-in queue()
, dequeue()
and delay()
, for example:
$(function() {
$('#yourElement')
.queue('myQueue', function() {
/* do stuff... */
// ...then tell jQuery to run the next method
// in the 'myQueue' queue in 2 seconds.
$(this).delay(2000, 'myQueue').dequeue('myQueue');
})
.queue('myQueue', function() {
/* do different stuff... */
// ...then tell jQuery to run the next method
// in the 'myQueue' queue in 2 seconds.
$(this).delay(2000, 'myQueue').dequeue('myQueue');
})
...
...
...
.dequeue('myQueue'); // run the first function in the queue.
})();
Typically, you enqueue all your functions and then do the initial call dequeue()
when you're done.
source to share