Javascript Reference Guide

 
 
This guide contains useful Javascript tips.







Timer.



Information
none

Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
    <title>Timer</title>
<script type="text/javascript" language="JavaScript">
timerID = 0;
tStart  = null;
tDiff = 0;
    
function UpdateTimer() {
    if(timerID) {
        clearTimeout(timerID);
    }
    
    if(!tStart) {
        tStart   = new Date();
    }
    
    var tDate = new Date();
    tDiff = tDate.getTime() - tStart.getTime();
     
    tDate.setTime(tDiff);
    
    hours = new String(tDate.getUTCHours());
    if(hours.length == 1) {
        hours = "0"+hours;
    }

    minutes = new String(tDate.getUTCMinutes());
    if(minutes.length == 1) {
        minutes = "0"+minutes;
    }

    
    seconds = new String(tDate.getUTCSeconds());    
    if(seconds.length == 1) {
        seconds = "0"+seconds;
    }
       
   document.theTimer.theTime.value = "" + hours + ":" + minutes + ":" + seconds;
   
   timerID = setTimeout("UpdateTimer()", 1000);
}

function Start() {
   tStart   = new Date();

   document.theTimer.theTime.value = "00:00:00";

   timerID  = setTimeout("UpdateTimer()", 1000);
}

function Stop() {
   if(timerID) {
      clearTimeout(timerID);
      timerID  = 0;
   }

   tStart = null;
}

function Reset() {
   tStart = null;

   document.theTimer.theTime.value = "00:00:00";
}

function Pause() {
    if(timerID) {
        clearTimeout(timerID);
        timerID  = 0;
    }
    
    if(document.theTimer.pause.value == "Pause") {
        document.theTimer.pause.value = "Resume"; 
    } else {
        document.theTimer.pause.value = "Pause"; 
        tToday = new Date();
        total_time = tToday.getTime() - tDiff;
        tStart = new Date(total_time);  
        timerID  = setTimeout("UpdateTimer()", 1000);
    } 
}
</script>
</head>

<body onload="Reset()" onunload="Stop()">
    <form action="javascript:void(null);" name="theTimer">
        <input type=text name="theTime" size="5" />
        <br /><br />
        <input type=button name="start" value="Start" onclick="Start()" />   
        <input type=button name="stop" value="Stop" onclick="Stop()" />   
        <input type=button name="reset" value="Reset" onclick="Reset()" />   
        <input type=button name="pause" value="Pause" onclick="Pause()" />
    </form>
</body>
</html>
Result