I am developing a quiz application in php and Javascript. The quiz starts when the user hits a submit button(I don't control when the quiz should start). The quiz should stop after a specific time (I decide that). I don't want to rely completely on the client computer to stop the time since the client pc time can be altered. The quiz should not restart on page refresh.
I know setInterval and basic javascript. The function I have developed so far works perfectly, but the quiz restarts on page refresh.
function formatSecondsAsTime(secs) {
var hours = Math.floor(secs / 3600);
var minutes = Math.floor(secs / 60) - (hours * 60);
var seconds = secs - (hours * 3600) - (minutes * 60);
return hours + ':' + minutes + ':' + seconds;
}
function startTimer(mytime) {
mytime = mytime.split(":");
hrs = mytime[0];
parseInt(hrs, 10);
mins = mytime[1];
parseInt(mins, 10)
secs = mytime[2];
parseInt(secs, 10);
if (hrs > 0 || mins > 0 || secs > 0) {
timerVar = setInterval(function () {
if (secs > 0) //time is less than a minute
{
displayTime(hrs, mins, secs--);
}
else if (secs == 0 && mins > 0) {
displayTime(hrs, mins = mins - 1, secs = secs + 59);
}
else if (secs == 0 && mins == 0 && hrs > 0) {
displayTime(hrs--, mins = mins + 59, secs = secs + 59);
}
else if (secs == 0 && mins == 0 && hrs == 0) {
clearTimeout(timerVar);
displayTime(0, 0, 0);
}
}, 1000);
}
else {
displayTime(0, 0, 0);
}
}
function displayTime(hrs, mins, secs) {
if (secs > 0 || hrs > 0 || mins > 0) {
if ((secs.toString()).length < 2) secs = "0" + secs;
if ((mins.toString()).length < 2) mins = "0" + mins;
if ((hrs.toString()).length < 2) hrs = "0" + hrs;
document.getElementById("quiztime").innerHTML = "Time remaining: " + hrs + ":" + mins + ":" + secs;
}
else {
document.getElementById("quiztime").innerHTML = "Quiz has ended!";
alert("Quiz has ended. Click ok to continue.");
document.forms["answerForm"].submit();
}
}
Please suggest me the best way to do it.
Thank you.