Skip to content

Instantly share code, notes, and snippets.

@gcchaan
Created August 6, 2013 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gcchaan/6166019 to your computer and use it in GitHub Desktop.
Save gcchaan/6166019 to your computer and use it in GitHub Desktop.
Stop Watch written in Javascript.
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>ストップウォッチ</title>
</head>
<body>
<div id="hour"></div>
<div id="minute"></div>
<div id="second">0.00</div>
<input type="button" value="スタート" id="run">
<input type="hidden" value="ストップ" id="stop">
<input type="button" value="リセット" id="reset">
<script>
var startTime,
stopTime,
diff,
timerId;
document.getElementById('run').onclick = function(){
runCount();
};
document.getElementById('stop').onclick = function(){
stopCount();
};
document.getElementById('reset').onclick = function(){
clearCount();
};
function runCount(){
if(stopTime){
startTime += (new Date()).getTime() - stopTime;
}
if(!startTime){
startTime = (new Date()).getTime();
}
timer();
document.getElementById('stop').type = "button";
document.getElementById('run').type = "hidden";
}
function timer(){
diff = ((new Date()).getTime() - startTime);
myH = Math.floor(diff / (60*60*1000));
diff -= myH*60*60*1000;
myM = Math.floor(diff / (60*1000));
diff -= (myM*60*1000);
if(myH > 0){document.getElementById('hour').innerHTML = myH + "時間";}
if(myM > 0){document.getElementById('minute').innerHTML = myM + "分";}
document.getElementById('second').innerHTML = (diff/1000).toFixed(2);
timerId = setTimeout(function(){
timer();
}, 100);
}
function stopCount(){
clearTimeout(timerId);
stopTime = (new Date()).getTime();
document.getElementById('run').type = "button";
document.getElementById('stop').type = "hidden";
}
function clearCount(){
stopCount();
startTime = undefined;
document.getElementById('hour').innerHTML = '';
document.getElementById('minute').innerHTML = '';
document.getElementById('second').innerHTML = '0.00';
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment