Web Development,
JavaScript, jQuery,
HTML and CSS stuff.

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 number of milliseconds of the timeout.
  • The second can be a function or a string
    • 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

try me

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 later more than once in a chain) unless you nest later using the second function argument.
  • In a chain, you can use the this keyword in an anonymous function's argument as usual.

Leave a comment

Your formating / indentation will be kept as-is.
Use HTML entities for special characters.
Allowed HTML tags: a, b, u, i, code
Syntax highlight: enclose code in <code></code>.

All code and content by Philippe Rathé is licensed under a Creative Commons Attribution 2.5 Canada License (unless otherwise mentioned).
Creative Commons License