1/** 2 * Manage delayed and timed actions 3 * 4 * @license GPL2 (http://www.gnu.org/licenses/gpl.html) 5 * @author Adrian Lang <lang@cosmocode.de> 6 */ 7 8/** 9 * Provide a global callback for window.setTimeout 10 * 11 * To get a timeout for non-global functions, just call 12 * delay.add(func, timeout). 13 */ 14var timer = { 15 _cur_id: 0, 16 _handlers: {}, 17 18 execDispatch: function (id) { 19 timer._handlers[id](); 20 }, 21 22 add: function (func, timeout) { 23 var id = ++timer._cur_id; 24 timer._handlers[id] = func; 25 return window.setTimeout('timer.execDispatch(' + id + ')', timeout); 26 } 27}; 28 29/** 30 * Provide a delayed start 31 * 32 * To call a function with a delay, just create a new Delay(func, timeout) and 33 * call that object’s method “start”. 34 */ 35function Delay (func, timeout) { 36 this.func = func; 37 if (timeout) { 38 this.timeout = timeout; 39 } 40} 41 42Delay.prototype = { 43 func: null, 44 timeout: 500, 45 46 delTimer: function () { 47 if (this.timer !== null) { 48 window.clearTimeout(this.timer); 49 this.timer = null; 50 } 51 }, 52 53 start: function () { 54 this.delTimer(); 55 var _this = this; 56 this.timer = timer.add(function () { _this.exec.call(_this); }, 57 this.timeout); 58 59 this._data = { 60 _this: arguments[0], 61 _params: Array.prototype.slice.call(arguments, 2) 62 }; 63 }, 64 65 exec: function () { 66 this.delTimer(); 67 this.func.call(this._data._this, this._data._params); 68 } 69}; 70