JSFiddle - React, Tailwind, and code Playground
by Al Kasih
HTML
<script src=" jquery-ui.css jquery-ui.js "></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<div id="time">
<span id="hours">00</span> :
<span id="minutes">00</span> :
<span id="seconds">00</span> ::
<span id="milliseconds">000</span>
</div>
<div id="controls">
<button id="start_pause_resume">Start</button>
<button id="reset">Reset</button>
</div>
CSS
body {
font-family:"Arial", Helvetica, sans-serif;
text-align: center;
}
#controls{
font-size: 12px;
}
#time {
font-size: 150%;
}
JavaScript
$(function() {
var hours = minutes = seconds = milliseconds = 0;
var prev_hours = prev_minutes = prev_seconds = prev_milliseconds = undefined;
var timeUpdate;
// Start/Pause/Resume button onClick
$("#start_pause_resume").button().click(function(){
// Start button
if($(this).text() == "Start"){ // check button label
$(this).html("<span class='ui-button-text'>Pause</span>");
updateTime(0,0,0,0);
}
// Pause button
else if($(this).text() == "Pause"){
clearInterval(timeUpdate);
$(this).html("<span class='ui-button-text'>Resume</span>");
}
// Resume button
else if($(this).text() == "Resume"){
prev_hours = parseInt($("#hours").html());
prev_minutes = parseInt($("#minutes").html());
prev_seconds = parseInt($("#seconds").html());
prev_milliseconds = parseInt($("#milliseconds").html());
updateTime(prev_hours, prev_minutes, prev_seconds, prev_milliseconds);
$(this).html("<span class='ui-button-text'>Pause</span>");
}
});
// Reset button onClick
$("#reset").button().click(function(){
if(timeUpdate) clearInterval(timeUpdate);
setStopwatch(0,0,0,0);
$("#start_pause_resume").html("<span class='ui-button-text'>Start</span>");
});
// Update time in stopwatch periodically - every 25ms
function updateTime(prev_hours, prev_minutes, prev_seconds, prev_milliseconds){
var startTime = new Date(); // fetch current time
timeUpdate = setInterval(function () {
var timeElapsed = new Date().getTime() - startTime.getTime(); // calculate the time elapsed in milliseconds
// calculate hours
hours = parseInt(timeElapsed / 1000 / 60 / 60) + prev_hours;
// calculate minutes
...