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.
One of the best ways to achieve this is the following: on the begin of the quiz, send an AJAX request to the server telling your PHP script that it’s started. Your PHP script should store a session variable for that user holding the start time. On submit of the quiz, check to make sure that the difference between the current time and the session stored start time is no greater than your allowed amount of time.
Session variables can’t be edited or viewed by the client. If the client loads the page in the middle of the quiz, set the JS timer amount to whatever time is left based on the start time in the session.