jQuery later plugin
Posted on november 27th, 2007
Avoid using setTimeout and benefits from jQuery chaining when using timeouts. I've taken this code from Douglas Crockford's teaching while he was extendting Object.prototype to accomplish such task. Unfortunately jQuery does not allow us to extend Object.prototype, but this can be done via extending the jQuery.fn object instead and that's called a jQuery plugin.
The plugin code
Passing arguments to later
-
The first argument is the
numberof milliseconds of the timeout. -
The second can be a
functionor astring-
function: Will be executed in the current chain context. -
string: The jQuery method name such as "addClass" or "hide".In that case all other arguments are optional and are passed as-is to the jQuery method's you are refering to.
-
Examples
Simple use
Nesting later
later Behavior
- Using later in a jQuery chains does not interupt the chain execution in any way.
-
The timeouts are calculated from the beginning of the chain execution, not from the last time a timeout was set (e.g. if you use
latermore than once in a chain) unless you nestlaterusing the secondfunctionargument. -
In a chain, you can use the
thiskeyword in an anonymous function's argument as usual.

Leave a comment