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