HTML code:
Copy Code code as follows:
<! DOCTYPE html>
<meta charset= "gb2312" >
<style type= "Text/css" >
#container {
margin:0 Auto;
margin-top:10%;
width:200px;
}
#timer {
Border:red double 1px;
width:180px;
height:76px;
line-height:76px;
font-size:32pt;
Color:green;
}
Input {
width:87px;
}
</style>
<body onload= "init ()" >
<div id= "Container" >
<div id= "Timer" ></div>
<input type= "button" id= "Ctrl"/>
<input type= "reset" onclick= "init ()"/>
</div>
</body>
JS Code:
Copy Code code as follows:
/*
* @author: Hyjiacan
*date:15:57 2010-9-5
*name:timer
*/
var ctrl = document.getElementById ("Ctrl"); Control button Object
var timer = document.getElementById ("timer"); Time Display Object
var hour, minute, second; When, the cent, the banknote
var T; SetTimeout method
Initializing Display and buttons
var init = function () {
timer.innerhtml = "00:00:00"; Because FF does not support the use of innertext, it uses innerHTML
hour = minute = Second = 0; Initialize display
Ctrl.setattribute ("Value", "Start"); Initialize control button text
Ctrl.setattribute ("onclick", "Startit ()"); Initializing control button Events
Cleartimeout (t);
}
Start the timer.
function Startit () {
t = settimeout ("Startit ()", 1000); Recursive call once every 1 seconds (1000 milliseconds)
second++;
if (second>=60) {//Judge seconds to 60, is the rounding
Second = 0;
minute++;
}
if (minute>=60) {//To determine whether the score is 60, is the rounding
minute = 0;
hour++;
}
timer.innerhtml = J (hour) + ":" + j (Minute) + ":" + j (second); Update display
Change Button status
Ctrl.setattribute ("Value", "Suspend/Stop"); Change button text
Ctrl.setattribute ("onclick", "Pause ()"); Change Button trigger Event
}
Display a number fill, that is, when the value shown is 0-9, fill 0 in front; such as: 1:0:4, then fill up to be 01:00:04
var j = function (ARG) {
Return arg>=10? ARG: "0" + arg;
}
Pause Timings
var pause = function () {
Cleartimeout (t);
Ctrl.setattribute ("onclick", "Startit ()");
Ctrl.setattribute ("value", "continue");
}
Use settimeout to handle it recursively. In this, there is a very important problem-latency, such practices and system CPU resources have a lot of relationship, and the function of the call will take time, and ultimately lead to the error of counting more and more big.
There is another way:
When the Start button is pressed, record the time (in milliseconds), and then read the current time every 1 seconds, minus the time that was recorded when the time was pressed, and the time elapsed.