Skip to content

Instantly share code, notes, and snippets.

/index.html Secret

Created July 9, 2016 23:53
Show Gist options
  • Save anonymous/cc4d58f244c585749a84503ad0e7fb18 to your computer and use it in GitHub Desktop.
Save anonymous/cc4d58f244c585749a84503ad0e7fb18 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Stopwatch</title>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<div class="stopwatch" id="main">00 : 00 . 00</div>
<div class="stopwatch miniwatch">00 : 00 . 00</div>
<div class="stopwatch miniwatch">00 : 00 . 00</div>
<div class="stopwatch miniwatch">00 : 00 . 00</div>
<div class="stopwatch miniwatch">00 : 00 . 00</div>
<button id="toggle">Toggle</button>
<script src="/js/stopwatch.js"></script>
<script src="/js/main.js"></script>
</body>
</html>
const button = document.querySelector('#toggle');
const mainWatch = document.querySelector('#main');
const miniWatches = document.querySelectorAll('.miniwatch');
const timer = new Stopwatch({ elem: mainWatch });
const miniTimers = [...miniWatches].map(elem => new Stopwatch({ elem }));
let step = 0;
button.addEventListener('click', () => {
if (step > 3) {
stopTimers();
step = 0;
return;
}
if (step === 0) {
resetTimers();
startTimers();
}
if (step > 0) {
updateMiniTimer();
}
step++;
})
function resetTimers () {
timer.reset();
miniTimers.forEach(timer => timer.reset());
}
function startTimers () {
timer.start();
miniTimers[0].start();
}
function stopTimers () {
timer.stop();
miniTimers[3].stop();
}
function updateMiniTimer () {
miniTimers[step - 1].stop();
miniTimers[step].start();
}
class Stopwatch {
constructor (opts) {
this.isOn = false;
this.time = 0;
this.elem = opts.elem;
}
start () {
this.offset = Date.now();
this.interval = setInterval(() => this._update(), 10);
this.isOn = true;
}
stop () {
clearInterval(this.interval);
this.offset = null;
this.interval = null;
this.isOn = false;
}
reset () {
this.time = 0;
this._render();
}
_update () {
this.time += this._getTimePassed();
this._render();
}
_getTimePassed () {
const now = Date.now();
const timePassed = now - this.offset;
this.offset = now;
return timePassed;
}
_timeFormatter (milliseconds) {
const padZero = (time) => `0${time}`.slice(-2);
const minutes = padZero(milliseconds / 60000 | 0);
const seconds = padZero((milliseconds / 1000 | 0) % 60);
const centiseconds = padZero((milliseconds / 10 | 0) % 100);
return `${minutes} : ${seconds} . ${centiseconds}`;
}
_render () {
this.elem.textContent = this._timeFormatter(this.time);
}
}
body {
text-align: center;
}
.stopwatch {
font-family: 'Lato';
font-weight: lighter;
margin: 20px;
}
.miniwatch {
font-size: 55px;
}
#main {
font-size: 115px;
}
button {
width: 125px;
height: 55px;
}
button:hover {
cursor: pointer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment