github.com/nicgrayson/terraform@v0.4.3-0.20150415203910-c4de50829380/website/source/assets/javascripts/lib/Chainable.js (about) 1 (function(){ 2 3 var Chainable = function(engine){ 4 this.engine = engine; 5 this._chain = []; 6 this._updateTimer = this._updateTimer.bind(this); 7 this._cycle = this._cycle.bind(this); 8 }; 9 10 Chainable.prototype._running = false; 11 12 Chainable.prototype._updateTimer = function(tick){ 13 this._timer += tick; 14 if (this._timer >= this._timerMax) { 15 this.resetTimer(); 16 this._cycle(); 17 } 18 }; 19 20 Chainable.prototype.resetTimer = function(){ 21 this.engine.updateChainTimer = undefined; 22 this._timer = 0; 23 this._timerMax = 0; 24 return this; 25 }; 26 27 Chainable.prototype.start = function(){ 28 if (this._running || !this._chain.length) { 29 return this; 30 } 31 this._running = true; 32 return this._cycle(); 33 }; 34 35 Chainable.prototype.reset = function(){ 36 if (!this._running) { 37 return this; 38 } 39 this.resetTimer(); 40 this._timer = 0; 41 this._running = false; 42 return this; 43 }; 44 45 Chainable.prototype._cycle = function(){ 46 var current; 47 if (!this._chain.length) { 48 return this.reset(); 49 } 50 51 current = this._chain.shift(); 52 53 if (current.type === 'function') { 54 current.func.apply(current.scope, current.args); 55 current = null; 56 return this._cycle(); 57 } 58 if (current.type === 'wait') { 59 this.resetTimer(); 60 // Convert timer to seconds 61 this._timerMax = current.time / 1000; 62 this.engine.updateChainTimer = this._updateTimer; 63 current = null; 64 } 65 66 return this; 67 }; 68 69 Chainable.prototype.then = Chainable.prototype.exec = function(func, scope, args){ 70 this._chain.push({ 71 type : 'function', 72 73 func : func, 74 scope : scope || window, 75 args : args || [] 76 }); 77 78 return this.start(); 79 }; 80 81 Chainable.prototype.wait = function(time){ 82 this._chain.push({ 83 type : 'wait', 84 time : time 85 }); 86 87 return this.start(); 88 }; 89 90 window.Chainable = Chainable; 91 92 })();