Sha256: 11b22bc8df966e94a368f6d24a7d487a94a67d71f413ee5dbe96dacf42a26b8c

Contents?: true

Size: 1.61 KB

Versions: 8

Compression:

Stored size: 1.61 KB

Contents

/**
	@class

	DelayedTask will execute a function after a delay.  Every time delay is called, any pending execution
	will be canceled.
*/
rio.DelayedTask = Class.create(/** @scope rio.DelayedTask.prototype */{
	/** @constructor */
	initialize: function() {
	    this.id = null;
		this.start = null;
		this.delayLength = null;
		this.task = null;
		this.args = [];
		this.scope = this;
	},

	/** @private */
    timeout: function() {
        if (new Date().getTime() - this.start >= this.delayLength) {
            clearInterval(this.id);
            this.id = null;
            this.task.apply(this.scope, this.args || []);
        }
    },

    /**
		Executes the passed in task after a delay.  This will also cancel any pending tasks.

		@param {Number} delayLength The delay in milliseconds
		@param {Function} task Task to execute after the delay
		@param {Object} scope (optional) The scope in which to execute the task
		@param {Array} args (optional) Arguments to pass into the task function 
     */
    delay: function(delayLength, task, scope, args) {
        if (this.id && delayLength != this.delayLength) {
            this.cancel();
        }
        
        this.delayLength = delayLength;
        this.task = task;
        this.scope = scope;
        this.args = args;
        
        this.start = new Date().getTime();
        
        if (!this.id) {
            this.id = setInterval(this.timeout.bind(this), this.delayLength);
        }
    },

    /**
     * Cancels the queued task
     */
    cancel: function() {
        if (this.id) {
            clearInterval(this.id);
            this.id = null;
        }
    }
});

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
riojs-0.0.7 public/javascripts/lib/delayed_task.js
riojs-0.0.6 public/javascripts/lib/delayed_task.js
riojs-0.0.5 public/javascripts/lib/delayed_task.js
riojs-0.0.4 public/javascripts/lib/delayed_task.js
riojs-0.0.3 public/javascripts/lib/delayed_task.js
riojs-0.0.2 public/javascripts/lib/delayed_task.js
riojs-0.0.1 public/javascripts/lib/delayed_task.js
riojs-0.0.0 public/javascripts/lib/delayed_task.js