Skip to content

Instantly share code, notes, and snippets.

@frankmeola
Last active August 29, 2015 14:25
Show Gist options
  • Save frankmeola/aa25a700f9786703dfd0 to your computer and use it in GitHub Desktop.
Save frankmeola/aa25a700f9786703dfd0 to your computer and use it in GitHub Desktop.
JavaScript Performance Analysis And The Mutating Interface: Part Two
var timer = stopwatch();
timer = timer.start();
setTimeout(function(){
timer = timer.stop();
console.log(timer.getElapsed().getMilliseconds());
}, 1500);
var timespan = function(milliseconds){
return {
_milliseconds:milliseconds,
getMilliseconds:function(){
return this._milliseconds;
},
getSeconds:function(){
return this.getMilliseconds() * 0.001;
},
getMinutes:function(){
return this.getSeconds() / 60;
}
};
};
var stopped = function(timings){
return {
timings:timings,
reset:function(){
return init();
},
restart:function(){
var reset = this.reset();
return reset.start();
},
getElapsed:function(){
return timespan(this.timings.stoppedOn - this.timings.startedOn);
}
};
};
var started = function(timings){
return {
timings:timings,
stop:function(){
return stopped({
startedOn:this.timings.startedOn,
stoppedOn:new Date()
});
},
reset:function(){
return init();
},
restart:function(){
var reset = this.reset();
return reset.start();
},
getElapsed:function(){
return timespan(new Date() - this.timings.startedOn);
}
};
};
var init = function(){
return {
start:function(){
return started({
startedOn:new Date(),
stoppedOn:null
});
},
getElapsed:function(){
return 0;
}
};
};
var stopwatch = function(){
return init();
};
var stopwatch = function(){
return {
//helper function to let us know if the stopwatch is stopped
_isStopped:function(){
return this.startedOn && this.stoppedOn;
},
//helper function to let us know if the stopwatch is running
_isRunning:function(){
return this.startedOn && !this.stoppedOn;
},
//start, stop, reset, and restart all seem like pretty common stopwatch function
start:function(){
this.startedOn = new Date();
},
stop:function(){
this.stoppedOn = new Date();
},
reset:function(){
this.startedOn = null;
this.stoppedOn = null;
},
restart:function(){
this.reset();
this.start();
},
//getElapsed has some tricks in it.
// - it needs to see if the stopwatch is running or not so we can return what you would expect
// - it uses Math.abs to ensure a positive number is always returned? why do we need that?
getElapsed : function(){
if(this._isStopped()) return Math.abs(this.stoppedOn - this.startedOn);
else if(this._isRunning()) Math.abs(new Date() - this.startedOn);
else return 0;
}
};
};
var timer = stopwatch();
timer.stop();
setTimeout(function(){
timer.start();
console.log(timer.getElapsed());
}, 1500);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment