<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>简单的计时器</title> </head> <body> <input type="button" id="start" onclick="startTime()" value="开始计时"/> <input type="button" id="stop" onclick="stopTime()" value="停止"/> <input type="button" onclick="clearTime()" value="清零"/> <p id="showTime">00 : 00 : 00 : 00</p> <script> var ms = 0; var secs = 0; var mins = 0; var hours = 0; var timeoutId; var isCounting = false; function startTime() { if(!isCounting) { isCounting = true; timeoutId = setInterval(countTime,10); //指定时间执行任务 } document.getElementById("start").value = "计时中"; } function stopTime() { if(isCounting) { isCounting = false; clearTimeout(timeoutId); //清除指定id计时器 document.getElementById("start").value = "继续"; } } function countTime() { ms+=1; if(ms>=100) { secs+=1; ms = 0; } if(secs>=60) { mins+=1; secs = 0; } if(mins>=60) { hours+=1; mins = 0; } if(hours>=24) { hours = 0; } // ms = checkTime(ms); // secs = checkTime(secs); // mins = checkTime(mins); // hours = checkTime(hours); document.getElementById("showTime").innerHTML = hours + " : " + mins + " : " + secs + " : " + ms; } function checkTime(time) { if(time<10) time = "0"+time; return time; } function resetTime() { ms = 0; secs = 0; mins = 0; hours = 0; } function clearTime() { resetTime(); document.getElementById("showTime").innerHTML = hours + " : " + mins + " : " + secs + " : " + ms; if(!isCounting) document.getElementById("start").value = "开始计时"; } </script> </body> </html>