htmlとjavascriptでストップウォッチ作ってみた
スポンサーリンク
仕事中,作業時間を計りたいと思い,ストップウォッチを作ってみました. かなりコードを削ったんですが,結局jqueryを使ってもjavascriptが80行. ただ,かなり殺風景なストップウォッチになりました.CSS必須です. 以下がhtmlとjavascriptのコードになります. jqueryはやっぱ便利ですね.
<!doctype html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="ja"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>stopwatch</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script> <script type="text/javascript" src="stopwatch1.js"></script> </head> <body> <div id="timeText">00"00'0.000</div> <input type="button" id="progressButton" value="▶"> <input type="button" id="resetButton" value="Reset"> </body> </html>
$(document).ready(function() { var isStopping = true; //停止中か var startTimeStamp = 0, stopTimeStamp = 0; //開始時刻,終了時刻1 var elapsedTime = 0; //経過時間 var progressButton = $('#progressButton'); var resetButton = $('#resetButton'); var timeText = $('#timeText'); var date = new Date(); //convertToHMSメソッドで使用 //design init var icons = {progress: "▶", stop: "||", reset:"Reset"}; progressButton.val(icons.progress); resetButton.val(icons.reset); //logic init progressButton.click(progress); resetButton.click(reset); timeText.click(progress); /** * 初期化する */ function initalize() { elapsedTime = 0; startTimeStamp = Date.now(); stopTimeStamp = Date.now(); timeText.html("0\"0'0.000"); } /** * 時計を進める/止めるボタンの動作 */ function progress(e) { if (isStopping) { //再開時 //止まっていた時間分開始時刻をすすめる startTimeStamp += Date.now() - stopTimeStamp; } else { //停止時 stopTimeStamp = Date.now(); } isStopping = !isStopping; //design ボタンアイコンの変更 if(isStopping) progressButton.val(icons.progress); else progressButton.val(icons.stop); } /** * 時計の時間をリセット */ function reset(e) { initalize(); } /** * ミリセカンドの整数を「時''分'秒.ミリ秒」形式に変換 (Dateオブジェクト使用) */ function convertToDateHMS(elapsedTime) { date.setTime(elapsedTime); var hour = date.getUTCHours(); var min = date.getUTCMinutes(); var sec = date.getUTCSeconds(); var msec = date.getUTCMilliseconds(); return hour + "\"" + min + "'" + sec + "." + msec; } /** * 逐次実行処理 */ function enterframe() { if (isStopping) { } else { elapsedTime = Date.now() - startTimeStamp; //design timeText.html(convertToDateHMS(elapsedTime)); } } initalize(); setInterval(enterframe, 1000 / 30); //1秒辺り30回処理 });
chromeで開くとこんなかんじになります.寂しい…