javascript - Simple counter with a listener and callback -
i have simple class below starts , updates count every second. how go adding functionality listen specific value , fire callback?
function counter() { this.currentcount = 0; } counter.prototype.start = function() { setinterval(this.update, 1000); }; counter.prototype.when = function(value, callback) { callback(value); }; counter.prototype.update = function() { this.currentcount++; };
in mind work this.
var counter = new counter(); counter.when(50, function(value) { console.log('we arrived @ ' + value + ', requested value.'); }); counter.start();
this nice homework, i'll ;) please have on solution:
function counter() { this.currentcount = 0; this.conditions = []; this.interval = undefined; } counter.prototype.start = function() { if (!this.interval) { var = this; this.interval = setinterval(function () { that.update(); }, 1000); } }; counter.prototype.stop = function () { if (this.interval) { clearinterval(this.interval); this.interval = undefined; } this.currentcount = 0; }; counter.prototype.when = function(value, callback) { var = this; this.conditions.push(function () { if (that.currentcount === value) { callback.call(that, value); } }); }; counter.prototype.update = function() { this.currentcount++; (var = 0, l = this.conditions.length; < l; i++) { var condition = this.conditions[i]; condition(); } }; var counter = new counter(); counter.when(50, function(value) { console.log('we arrived @ ' + value + ', requested value.'); }); counter.when(60, function (value) { console.log('stop @ ' + value + '!'); this.stop(); }); counter.start();
and it's fiddled!
another answer here made argument in hiding private variables, implemented bit confused, way of doing similar. instead of shared prototype functions using instance functions. may needs more memory, don't believe it's significant, , allows have privates in real constructor function.
var counter = function () { var = this, currentcount = 0, conditions = [], interval; var update = function () { currentcount++; (var = 0, l = conditions.length; < l; i++) { var condition = conditions[i]; condition(); } }; this.start = function () { if (!interval) { interval = setinterval(function() { update.call(that); }, 1000); } }; this.when = function (value, callback) { conditions.push(function () { if (currentcount === value) { callback.call(that, value); } }); }; this.stop = function () { if (interval) { clearinterval(interval); interval = undefined; } currentcount = 0; }; }; var counter = new counter(); counter.when(50, function(value) { console.log('we arrived @ ' + value + ', requested value.'); }); counter.when(60, function (value) { console.log('stop @ ' + value + '!'); this.stop(); }); counter.start();
see fiddled!
notice in both examples, counter
instanceof counter
, object
,
whereas counter
instanceof function
, object
(why write code ;))
Comments
Post a Comment