Use setTimeout for Recursive processing. In this case, there is a very important problem-latency. This method has a lot to do with the system CPU resources, and it takes time to call functions, in the end, the error in counting is getting bigger and bigger. html code:
The Code is as follows:
Js Code:
The Code is 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; // hour, minute, banknote
Var t; // setTimeout Method
// Initialize the display and button
Var init = function (){
Timer. innerHTML = "00:00:00"; // because FF does not support innerText, innerHTML
Hour = minute = second = 0; // initialization display
Ctrl. setAttribute ("value", "Start"); // initialize the control button text
Ctrl. setAttribute ("onclick", "startit ()"); // initialize the control button event
ClearTimeout (t );
}
// Start timing
Function startit (){
T = setTimeout ("startit ()", 1000); // recursive call once every 1 second (1000 milliseconds)
Second ++;
If (second> = 60) {// determines whether the second reaches 60. if yes, the carry
Second = 0;
Minute ++;
}
If (minute> = 60) {// determines whether the score reaches 60. if yes, it indicates the carry.
Minute = 0;
Hour ++;
}
Timer. innerHTML = j (hour) + ":" + j (minute) + ":" + j (second); // update display
// Change the button status
Ctrl. setAttribute ("value", "Pause/Stop"); // modify button text
Ctrl. setAttribute ("onclick", "pause ()"); // The event triggered by the change button.
}
// Fill in the display number, that is, when the displayed value is 0-9, fill 0 in the front; for example: 1: 0: 4, fill into 01:00:04
Var j = function (arg ){
Return arg> = 10? Arg: "0" + arg;
}
// Pause the timer
Var pause = function (){
ClearTimeout (t );
Ctrl. setAttribute ("onclick", "startit ()");
Ctrl. setAttribute ("value", "continue ");
}
Use setTimeout for Recursive processing. In this case, there is a very important problem-latency. This method has a lot to do with the system CPU resources, and it takes time to call functions, in the end, the counting error increases.
There is another method:
When you press the start button, record the press time (in milliseconds), then read the current time every one second, and then use the current time minus the time recorded during the press, calculate the elapsed time.