initial import
[roojs1] / Roo / util / DelayedTask.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11
12 /**
13  * @class Roo.util.DelayedTask
14  * Provides a convenient method of performing setTimeout where a new
15  * timeout cancels the old timeout. An example would be performing validation on a keypress.
16  * You can use this class to buffer
17  * the keypress events for a certain number of milliseconds, and perform only if they stop
18  * for that amount of time.
19  * @constructor The parameters to this constructor serve as defaults and are not required.
20  * @param {Function} fn (optional) The default function to timeout
21  * @param {Object} scope (optional) The default scope of that timeout
22  * @param {Array} args (optional) The default Array of arguments
23  */
24 Roo.util.DelayedTask = function(fn, scope, args){
25     var id = null, d, t;
26
27     var call = function(){
28         var now = new Date().getTime();
29         if(now - t >= d){
30             clearInterval(id);
31             id = null;
32             fn.apply(scope, args || []);
33         }
34     };
35     /**
36      * Cancels any pending timeout and queues a new one
37      * @param {Number} delay The milliseconds to delay
38      * @param {Function} newFn (optional) Overrides function passed to constructor
39      * @param {Object} newScope (optional) Overrides scope passed to constructor
40      * @param {Array} newArgs (optional) Overrides args passed to constructor
41      */
42     this.delay = function(delay, newFn, newScope, newArgs){
43         if(id && delay != d){
44             this.cancel();
45         }
46         d = delay;
47         t = new Date().getTime();
48         fn = newFn || fn;
49         scope = newScope || scope;
50         args = newArgs || args;
51         if(!id){
52             id = setInterval(call, d);
53         }
54     };
55
56     /**
57      * Cancel the last queued timeout
58      */
59     this.cancel = function(){
60         if(id){
61             clearInterval(id);
62             id = null;
63         }
64     };
65 };