|
| 1 | +# [jQuery Timeout](https://github.com/tkem/jquery-timeout/) |
| 2 | + |
| 3 | +**jQuery 1.5** introduced the _Deferred_ callback management system, |
| 4 | +to ease handling callbacks for asynchronous events. Although the |
| 5 | +jQuery documentation contains examples on how to use deferred objects |
| 6 | +with the native `window.setTimeout` and `window.clearTimeout` |
| 7 | +functions, jQuery does not provide a simple interface for timer-based |
| 8 | +deferreds by its own. |
| 9 | + |
| 10 | +This plugin provides the two functions `jQuery.timeout` and |
| 11 | +`jQuery.timeoutWith` that, given a delay in milliseconds, create a |
| 12 | +`jQuery.Deferred` instance that will be resolved after the given |
| 13 | +delay. The returned _promise_ object also provides `clear` and |
| 14 | +`clearWith` methods, which will reject the deferred object and clear |
| 15 | +the native timeout ID, if called before the timeout has elapsed. |
| 16 | + |
| 17 | + |
| 18 | +## API Documentation |
| 19 | + |
| 20 | +### jQuery.timeout( delay [, args ] ) |
| 21 | + |
| 22 | +Return a Promise object that will be resolved after the given `delay`. |
| 23 | + |
| 24 | +### jQuery.timeoutWith( delay, context [, args ] ) |
| 25 | + |
| 26 | +Return a Promise object that will be resolved after the given `delay`. |
| 27 | + |
| 28 | +### timeout.clear( [ args ] ) |
| 29 | + |
| 30 | +Reject a Deferred timeout object. |
| 31 | + |
| 32 | +### timeout.clearWith( context [, args ] ) |
| 33 | + |
| 34 | +Reject a Deferred timeout object. |
| 35 | + |
| 36 | + |
| 37 | +## Examples |
| 38 | + |
| 39 | +Invoke a callback function after a five-second delay: |
| 40 | + |
| 41 | +``` |
| 42 | + $.timeout(5000, $("#status"), "5 seconds").done(function($e, msg) { |
| 43 | + $e.text(msg + " later..."); |
| 44 | + }); |
| 45 | +``` |
| 46 | + |
| 47 | +Provide handlers to be called when the timeout is resolved (elapsed) |
| 48 | +or rejected (cleared), and an event handler to manually clear the |
| 49 | +timeout. |
| 50 | + |
| 51 | +``` |
| 52 | + var timeout = $.timeout(10000); |
| 53 | +
|
| 54 | + timeout.then( |
| 55 | + function() { alert("timeout elapsed") }, |
| 56 | + function() { alert("timeout cleared") } |
| 57 | + ); |
| 58 | +
|
| 59 | + $("#clear").click(function() { |
| 60 | + timeout.clear(); |
| 61 | + }); |
| 62 | +``` |
0 commit comments