Timer
by wio_dude
HTML
<form>
<input id="rep-count" type="text" value="20" />
<input id="time-per-rep" type="text" value="3" />
<input id="start" type="button" value="start" />
<input id="pause" type="button" value="pause" />
</form>
<div id="rep-display">
<span id="rep-elapsed">0</span>
/
<span id="rep-total">0</span>
</div>
<div id="time-display">
<span id="time-elapsed">0</span>
/
<span id="time-total">0</span>
</div>
JavaScript
var input = {};
input.start = document.getElementById('start');
input.pause = document.getElementById('pause');
input.repCount = document.getElementById('rep-count');
input.timePerRep = document.getElementById('time-per-rep');
input.repElapsed = document.getElementById('rep-elapsed');
input.repTotal = document.getElementById('rep-total');
input.timeElapsed = document.getElementById('time-elapsed');
input.timeTotal = document.getElementById('time-total');
var timeKeeper = null;
input.start.addEventListener('click', function() {
var totalReps = parseInt(input.repCount.value, 10);
var totalTime = parseInt(input.timePerRep.value, 10) * totalReps;
input.repTotal.innerHTML = totalReps;
input.timeTotal.innerHTML = totalTime;
timeKeeper = new Timer(totalTime * 1000);
timeKeeper.begin();
});
input.pause.addEventListener('click', function() {
if (timeKeeper.isPaused()) {
timeKeeper.unpause();
} else {
timeKeeper.pause();
}
});
function Timer(duration) {
this.elapsed = 0;
this.duration = duration;
this.startTS = null;
this.finishTS = null;
this.pauses = [];
this.pauseDuration = 0;
}
Timer.prototype.begin = function() {
this.startTS = Date.now();
this.effectiveStartTS = this.startTS;
};
Timer.prototype.update = function() {
this.elapsed = Date.now() - this.effectiveStartTS;
};
Timer.prototype.pause = function() {
this.pauses.push([Date.now()]);
};
Timer.prototype.isStarted = function() {
return this.startTS !== null;
};
Timer.prototype.isPaused = function() {
if (this.pauses.length > 0) {
return this.pauses[this.pauses.length].lenght === 1;
}
return false;
};
Timer.prototype.isFinished = function() {
return this.elapsed >= this.duration;
};
Timer.prototype.isRunning = function() {
return this.isStarted() && !this.isPaused() && this.isFinished();
}
function update() {
if (timeKeeper) {
timeKeeper.update();
var totalReps =...