Thursday, July 19, 2007

Javascript for setting a timer for a page

Javascript for setting a timer for a page. It automatically submits the form to the next page.... This javascript code displays the timer in the taskbar.

var timerID = null;
var timerRunning = false;
var secondsleft = null;

function stopclock() {
if (timerRunning) {
clearTimeout(timerID);
timerRunning = false;
}
}

function startclock(s) {
secondsleft=s;
stopclock();
showtime();
}

function showtime() {
secondsleft = secondsleft - 1;
if (secondsleft == 60) {
alert("1 minute left");
}
if (secondsleft == 0) {
stopclock();
document.title ="Time over";
alert("Sorry Time's up");
window.document.getElementById("id_submitbutton").click();
//document.getElementById("mform1").submit();
} else {
current = secondsleft;
var hours = Math.floor( current / 3600 );
current = current - (hours*3600);
var minutes = Math.floor( current / 60 );
current = current - (minutes*60);
var seconds = current;
var timeValue = "" + hours;
timeValue += ((minutes < 10) ? ":0" : ":") + minutes;
timeValue += ((seconds < 10) ? ":0" : ":") + seconds;
document.title = timeValue;
timerID = setTimeout("showtime()",1000);
timerRunning = true;
}
}

-----------------------------------------------------

In the above code, we can use either
window.document.getElementById("id_submitbutton").click();
or
document.getElementById("mform1").submit();

No comments: