github.com/chalford/terraform@v0.3.7-0.20150113080010-a78c69a8c81f/website/source/assets/javascripts/lib/Chainable.js (about)

     1  (function(){
     2  
     3  var Chainable = function(){
     4  	this._chain = [];
     5  	this._cycle = this._cycle.bind(this);
     6  };
     7  
     8  Chainable.prototype._running = false;
     9  
    10  Chainable.prototype.start = function(){
    11  	if (this._running || !this._chain.length) {
    12  		return this;
    13  	}
    14  	this._running = true;
    15  	return this._cycle();
    16  };
    17  
    18  Chainable.prototype.reset = function(){
    19  	if (!this._running) {
    20  		return this;
    21  	}
    22  	clearTimeout(this._timer);
    23  	this._timer = null;
    24  	this._chain.length = 0;
    25  	this._running = false;
    26  	return this;
    27  };
    28  
    29  Chainable.prototype._cycle = function(){
    30  	var current;
    31  	if (!this._chain.length) {
    32  		return this.reset();
    33  	}
    34  
    35  	current = this._chain.shift();
    36  
    37  	if (current.type === 'function') {
    38  		current.func.apply(current.scope, current.args);
    39  		current = null;
    40  		return this._cycle();
    41  	}
    42  	if (current.type === 'wait') {
    43  		clearTimeout(this._timer);
    44  		this._timer = setTimeout(this._cycle, current.time || 0);
    45  		current = null;
    46  	}
    47  
    48  	return this;
    49  };
    50  
    51  Chainable.prototype.then = Chainable.prototype.exec = function(func, scope, args){
    52  	this._chain.push({
    53  		type  : 'function',
    54  
    55  		func  : func,
    56  		scope : scope || window,
    57  		args  : args  || []
    58  	});
    59  
    60  	return this.start();
    61  };
    62  
    63  Chainable.prototype.wait = function(time){
    64  	this._chain.push({
    65  		type : 'wait',
    66  		time : time
    67  	});
    68  
    69  	return this.start();
    70  };
    71  
    72  window.Chainable = Chainable;
    73  
    74  })();