Reputation: 281
Helllo, I'm making a quiz application, and want to set a timer. I want to make it in Javascript. This is my function:
function countDown(sec, elem) {
_(elem).innerHTML = sec;
if(sec < 1) {
clearTimeout(timer);
endGame ();
return;
}
sec--;
var timer = setTimeout('countDown('+sec+',"'+elem+'")',1000);
}
The problem is that, for example, for mobile Saffari browser, when you hold your finger on the screen (like scrolling effect), the timer stops, yet you can still see the questions... So, basically, you can have an unlimited time. How can I make the timer to run nomatter what?
Thank you in advance!
Upvotes: 1
Views: 667
Reputation:
You could always check the Date
whenever the timer event does fire. Something like:
var timerStart = function(timeLimit) {
var remaining = timeLimit, h, m, s;
var startTime = +new Date();/*Date.now();*/
var instance = function() {
if (remaining > 0) {
remaining = timeLimit - ((+new Date()) - startTime);
h = Math.floor(remaining / 3600000);
m = Math.floor(remaining % 3600000 / 60000);
s = Math.floor(remaining % 3600000 % 60000 / 1000);
window.setTimeout(instance, 1000);
} else {
/* do whatever you need to do when time is up */
}
}
instance();
}
Upvotes: 0
Reputation: 3034
You can't make the time run 'no matter what' - Mobile Safari will not run setTimeout and setInterval function calls during touch events. In fact, prior to iOS6, the events are discarded completely.
You should instead sanity check with the Date constructor, and perform server-side validation. If someone really wants to cheat, they can, after all, modify your JavaScript on the client.
Upvotes: 1