html code:
js code:
/*
*@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, currency
var t; //setTimeout method
// Initialize display and buttons
var init = function(){
timer.innerHTML = "00:00:00"; //Since FF does not support the use of innerText, innerHTML is used
hour = minute = second = 0; //Initialize display
ctrl.setAttribute("value", "start"); //Initialize control button text
ctrl.setAttribute("onclick", "startit()"); //Initialize control Button event
clearTimeout(t);
}
//Start timing
function startit(){
t = setTimeout("startit()", 1000); //Every 1 Second (1000 milliseconds) recursively call
second ;
if(second>=60){ // Determine whether the second reaches 60, if so, carry
second = 0;
minute ;
}
if(minute>=60){ //Determine whether the score reaches 60, if so, carry
minute = 0;
hour ;
}
timer.innerHTML = j(hour) ":" j(minute) ":" j(second) ; //Update display
//Change button status
ctrl.setAttribute("value", "Pause/Stop"); //Change button text
ctrl.setAttribute("onclick", "pause()"); //Change button trigger event
}
//Display number padding, that is, when the displayed value is 0-9, in front Fill in 0; for example: 1:0:4, then fill in 01:00:04
var j = function(arg){
return arg>=10 ? arg : "0" arg;
}
//Pause timing
var pause = function(){
clearTimeout(t);
ctrl.setAttribute("onclick", "startit()");
ctrl.setAttribute( "value", "continue");
}
Use setTimeout for recursive processing. Among them, there is a very important issue - delay. This approach has a lot to do with the system CPU resources, and the function call also takes time, which ultimately leads to increasing counting errors.
There is another method:
When pressing the start button, record the pressing time (milliseconds), then read the current time every 1 second, and then use the current Calculate the elapsed time by subtracting the time noted when pressing.