The jQuery later “plugin”
You can extend jQuery.fn by assigning a later function to it to avoid always defining a callback function just to use setTimeout. later returns the object that called the function, so it do not breaks the chainability magic in jQuery.
The later plugin for jQuery
[ Thanks to Douglas Crockford for his teaching ]
var that = this;
var args = Array.prototype.slice.apply(arguments, [2]);
if (typeof method === "string") {
method = that[method];
}
setTimeout(function () {
method.apply(that, args);
}, msec);
return that;
};
It was almost my first plugin, but that is too short to make it a plugin :-)
It is more likely a feature. Let’s see examples of how to use it.
Samples of use for the later function
$(‘#myid’).before("Saved!")
.prev().later(3000, "hide");
// Show "Saved!" for 3 seconds, hiding slowly
$(‘#myid’).before("Saved!")
.prev().later(3000, "hide", "slow");
// Chaining later …
// Change the appearance of the list for 4 seconds,
// show a "saved" notice before it
// and fade it slowly 3 seconds after if appears
$(‘#list_id’)
.addClass("success")
.later(4000, "removeClass", "success")
.before("Saved!")
.prev()
.later(7000, "fadeOut", "slow");
When *not* to use it
- If you want to call a jQuery function right after an effect has finished, use the jQuery callback instead
- If you are unsure that the function called by
laterwill be executed after the previous one has finished and that the order matters
When to use it
- If you can’t or don’t want to use the jQuery callback function
- You would use the jQuery callback function just to use the
setTimeoutfunction to join two actions that are not dependent - When you can control the exact sequence of execution and you are sure it will be executed in that order
I’ve post a small article on using the later method with your own object. Read it.