var Regulator = function(callback, callbackEnd, init) { this.k = 0.15; this.val = init ? init : 0; this.timer = null; this.callback = callback; this.callbackEnd = callbackEnd ? callbackEnd : null; this.min = null; this.max = null; this.delay = 20; this.newVal = 0; this.enabled = false; } Regulator.prototype.setVal = function(val) { this.val = val; } Regulator.prototype.setK = function(k) { this.k = k; } Regulator.prototype.setMin = function(min) { this.min = min; } Regulator.prototype.setMax = function(max) { this.max = max; } Regulator.prototype.start = function(newVal) { this.enabled = true; this.newVal = newVal; this.iter(); } Regulator.prototype.iter = function() { if(this.enabled) { var d = this.newVal - this.val; var e = this.k * d; this.val += e; if(this.min !== null) { this.val = Math.max(this.val, this.min); } if(this.max !== null) { this.val = Math.min(this.val, this.max); } this.callback(this.val); if(Math.abs(d) >= 0.5) { var self = this; this.timer = setTimeout(function() { self.iter(); }, this.delay); } else { if(this.callbackEnd) { this.callbackEnd(); } } } } Regulator.prototype.stop = function() { this.enabled = false; clearTimeout(this.timer); }