Skip to content

Instantly share code, notes, and snippets.

@cfpg
Created November 12, 2009 00:04
Show Gist options
  • Save cfpg/232448 to your computer and use it in GitHub Desktop.
Save cfpg/232448 to your computer and use it in GitHub Desktop.
function buildTime(t) {
minutes = t.getMinutes();
seconds = t.getSeconds();
hours = t.getHours();
if (minutes < 10) {
minutes = "0"+minutes;
}
if (seconds < 10) {
seconds = "0"+seconds;
}
if (hours > 0) {
return hours+":"+minutes+":"+seconds;
} else {
return minutes+":"+seconds;
}
}
// Call this to start the timer
function startTimer() {
// If time isn't an object, create new Date and set seconds/minutes to 0
if (typeof(time) != "object") {
time = new Date();
time.setSeconds(0); // Sets seconds to 0
time.setMinutes(0); // Sets minutes to 0
document.getElementById("show_timer_div").innerHTML = buildTime(time); // buildTime(time) returns 00:00
}
// Update seconds, to be executed every second or 1000 miliseconds
function changeTimer() {
time.setSeconds(time.getSeconds()+1);
document.getElementById("show_timer_div").innerHTML = buildTime(time);
}
// Set Interval to every second
interval = setInterval(changeTimer, 1000);
}
// Pauses timer, seconds/minute count will be the same when started again
function pauseTimer() {
clearInterval(interval);
}
// Reset timer to 00:00
function resetTimer() {
time = ""; // Turn time into a string
clearInterval(interval); // Clear interval
document.getElementById("show_timer_div").innerHTML = "00:00"; // Put timer to 0's
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment