javascriptでストップウォッチ
ドットインストールでやったストップウォッチを改良。
ストップを押したときしか時間が表示されないのを
リアルタイムで表示されるようにした。
正しいjsの書き方がよくわからない。
関数式にすると巻き上げが起こらないからaddEventListnerを下の方に書かなくちゃいけなくなって、読みづらくなる気がする。
載せる際に面倒なのでcss,jsともにhtmlにまとめた
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ストップウォッチ</title> <style> #container { text-align: center; width: 300px; margin: 30px auto 0; font-weight: bold; } #stopwatch { font-size: 30px; padding: 50px 0; border: 2px #000000 solid; border-radius: 10px; } #startStop,#clear { cursor: pointer; font-size: 18px; width: 145px; background: #eee; height: 40px; line-height: 40px; } #startStop { float: left; } #clear { float: right; } </style> <body> <div id="container"> <div id="stopwatch"> <div id="display">0.000</div> </div> <div class="buttons"> <button id="startStop">スタート</button> <button id="clear">クリア</button> </div> </div> <script> document.addEventListener('DOMContentLoaded', () => { document.getElementById('startStop').addEventListener('click', main_stopWatch); document.getElementById('clear').addEventListener('click', clear_stopWatch); let isStarted = false, stopTime, startTime, pendTime = 0, stopWatchId; let disp = document.getElementById('display'); let startStop = document.getElementById('startStop'); function main_stopWatch() { isStarted = !isStarted; isStarted ? start_stopWatch() : stop_stopWatch(); } function start_stopWatch() { startStop.innerHTML = 'ストップ'; dispTime(); stopWatchId = setInterval(dispTime, 1); } function dispTime() { startTime = startTime || Date.now(); stopTime = Date.now() - startTime + pendTime; disp.innerHTML = (stopTime / 1000).toFixed(3); } function stop_stopWatch() { startStop.innerHTML = 'スタート'; clearInterval(stopWatchId); startTime = null; pendTime = stopTime; } function clear_stopWatch() { stop_stopWatch(); pendTime = 0; disp.innerHTML = '0.000'; } }) </script> </body> </html>