A javascript clock [Vanilla JS]
A simple javascript clock
by jjperezaguinaga
HTML
<div> <em id="hours">00</em>:<em id="minutes">00</em>:<em id="seconds">00</em>
<br/>
<button id="pause">Pause</button>
<button id="resume">Resume</button>
<button id="reset">Reset</button>
</div>
JavaScript
var Clock = {
seconds: 23,
minutes: 59,
hours: 23,
displayNumber: function (n, type) {
this[type] = n;
var formattedNumber = (n).toString().length == 1 ? "0" + n : n;
document.getElementById(type).innerHTML = formattedNumber;
},
increase: function () {
this.seconds = parseInt(this.seconds) + 1;
this.displayNumber((parseInt((parseInt(+this.seconds / 60) + +this.minutes) / 60) + +this.hours) % 24, "hours");
this.displayNumber((parseInt(+this.seconds / 60) + +this.minutes) % 60, "minutes");
this.displayNumber(this.seconds % 60, "seconds");
},
start: function () {
var that = this;
this.interval = setInterval(function () {
that.increase();
}, 1000)
},
pause: function() {
clearInterval(this.interval); delete this.interval;
},
resume: function() {
if(!this.interval) this.start();
},
reset: function() {
this.seconds = 0; this.minutes = 0; this.hours = 0;
}
}
Clock.start();
document.getElementById("pause").addEventListener("click", Clock.pause.bind(Clock));
document.getElementById("reset").addEventListener("click", Clock.reset.bind(Clock));
document.getElementById("resume").addEventListener("click", Clock.resume.bind(Clock));