<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>timer-计时器</title> <style> div{ width:300px; margin:0 auto; padding-top:60px; } #timer{ font-size:30px; text-align:center; } #start{ font-weight:bold; } </style> <script> var intervalId, //setInterval的id pattern = /^d$/, //正则模式,匹配单个数值 intervalSeconds = 1000, //调用setInterval的间隔时间,设置为 1000 毫秒,即 1 秒 secondIncrement = 0; //设置秒递增器起始值为 0 //注册页面加载事件 window.onload = function () { var start = document.getElementById("start"); var timer = document.getElementById("timer"); function handleTimer() { if (!intervalId) { intervalId = setInterval(function () { secondIncrement++;
//定义一个Date对象实例 var someDate = new Date("1111/1/1,0:0:0");
//设置秒数,当secondIncrement值超过59时,则分钟数会加1 someDate.setSeconds(secondIncrement); var hours = someDate.getHours(); hours = pattern.test(hours) ? "0" + hours + ":" : hours + ":"; var minutes = someDate.getMinutes(); minutes = pattern.test(minutes) ? "0" + minutes + ":" : minutes + ":"; var seconds = someDate.getSeconds(); seconds = pattern.test(seconds) ? "0" + seconds : seconds; timer.value = hours + minutes + seconds; }, intervalSeconds); this.innerHTML = "Pause"; } else { clearInterval(intervalId); intervalId = null; this.innerHTML = "Start"; } } start.addEventListener("click", handleTimer, false); } </script> </head> <body> <div> <p><input type="text" id="timer" value="00:00:00" readonly/></p> <button id="start">Start</button> </div> </body> </html>