1 /** 2 @class 3 4 DelayedTask will execute a function after a delay. Every time delay is called, any pending execution 5 will be canceled. 6 */ 7 rio.DelayedTask = Class.create(/** @scope rio.DelayedTask.prototype */{ 8 /** @constructor */ 9 initialize: function() { 10 this.id = null; 11 this.start = null; 12 this.delayLength = null; 13 this.task = null; 14 this.args = []; 15 this.scope = this; 16 }, 17 18 /** @private */ 19 timeout: function() { 20 if (new Date().getTime() - this.start >= this.delayLength) { 21 clearInterval(this.id); 22 this.id = null; 23 this.task.apply(this.scope, this.args || []); 24 } 25 }, 26 27 /** 28 Executes the passed in task after a delay. This will also cancel any pending tasks. 29 30 @param {Number} delayLength The delay in milliseconds 31 @param {Function} task Task to execute after the delay 32 @param {Object} scope (optional) The scope in which to execute the task 33 @param {Array} args (optional) Arguments to pass into the task function 34 */ 35 delay: function(delayLength, task, scope, args) { 36 if (this.id && delayLength != this.delayLength) { 37 this.cancel(); 38 } 39 40 this.delayLength = delayLength; 41 this.task = task; 42 this.scope = scope; 43 this.args = args; 44 45 this.start = new Date().getTime(); 46 47 if (!this.id) { 48 this.id = setInterval(this.timeout.bind(this), this.delayLength); 49 } 50 }, 51 52 /** 53 * Cancels the queued task 54 */ 55 cancel: function() { 56 if (this.id) { 57 clearInterval(this.id); 58 this.id = null; 59 } 60 } 61 });