Moment.js Stopwatch
Another JavaScript stopwatch built with unusual methods.
by michaelschmid
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>
<div id="stopwatch">
<div id="time-container" class="container"></div>
<button class="button" id="start">Start</button>
<button class="button" id="stop">Stop</button>
</div>
SCSS
*,
*:before,
*:after, {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
body {
margin: 0 auto;
width: 20em;
}
.stopwatch {
background: #C0FFEE;
font-family: Helvetica, Arial, sans-serif;
font-size: 2rem;
width: 100%;
height: 2em;
}
.container {
margin: 0 auto;
padding: 0.4em;
width: 60%;
height: 100%;
color: #111;
}
.button {
background: #BADA55;
border: none;
cursor: pointer;
display: inline-flex;
flex-direction: row-reverse;
justify-content: space-between;
margin-top: 0.2em;
margin-right: 1%;
padding: 0.3em;
width: 48%;
text-align: center;
transition: all 0.3s ease;
}
.button:hover,
.button:focus {
background: #FFF;
color: #BADA55;
font-weight: 700;
}
.button:last-child {
background: #E00;
color: #FFF;
margin-right: 0;
}
.button:last-child:hover,
.button:last-child:focus {
background: #FFF;
color: #E00;
font-weight: 700;
}
JavaScript
var AppStopwatch = (function () {
var counter = 0,
$stopwatch = {
el: document.getElementById('stopwatch'),
container: document.getElementById('time-container'),
startControl: document.getElementById('start'),
stopControl: document.getElementById('stop')
};
var runClock;
function displayTime() {
$stopwatch.container.innerHTML = moment().hour(0).minute(0).second(counter++).format('HH : mm : ss');
}
function startWatch() {
runClock = setInterval(displayTime, 1000);
}
function stopWatch() {
clearInterval(runClock);
}
return {
startClock: startWatch,
stopClock: stopWatch,
$start: $stopwatch.startControl,
$stop: $stopwatch.stopControl
};
})();
AppStopwatch.$start.addEventListener('click', AppStopwatch.startClock, false);
AppStopwatch.$stop.addEventListener('click', AppStopwatch.stopClock, false);