Reputation: 22974
This is my snippet.
$(function() {
setCountDown(0, 1, 0);
a = Array();
$(window).bind('beforeunload', function() {
if (a['endTime']) {
return ("You are in the middle of a test");
}
});
});
function setCountDown(hours, minutes, seconds) {
$(".timer").removeClass("common_displayNone");
timerInterval = setInterval(
function() {
if (hours.toString().length == 1) {
hours = "0" + hours;
}
if (minutes.toString().length == 1) {
minutes = "0" + minutes;
}
if (seconds.toString().length == 1) {
seconds = "0" + seconds;
}
if (seconds > 0) {
seconds--;
if (seconds.toString().length == 1) {
seconds = "0" + seconds;
}
} else if (seconds == 0 && (minutes > 0)) {
minutes = minutes - 1;
seconds = 59;
} else if (minutes == 0 && (hours > 0)) {
hours = hours - 1;
minutes = 59;
}
if (hours == 0 && minutes == 0 && seconds == 0) {
clearInterval(timerInterval);
a.removeItem("endTime");
}
$("#timer").html(hours + ":" + minutes + ":" + seconds);
a['endTime'] = (hours * 3600 + minutes * 60 + seconds);
}, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timer"></div>
Just try to reload the page. You will get an alert. During that alert, my timers are not running. So user can cheat test. How to solve this issue?
Upvotes: 4
Views: 1173
Reputation: 2855
Javascript is a single threaded language, which means that you cannot have code running on the "background". When javascript prompts an alert window, it waits for the user to click "Ok".
If you really want to have popups, you'll have to do it with HTML and CSS.
I'd recommend handling the time a user has for his test server side if you're worried about cheating, because a user can still edit your javascript allowing himself to take more time. You could accomplish this with websockets or polling.
Upvotes: 2
Reputation: 3052
JavaScript is usually considered to have a single thread of execution visible to scripts(*), so that when your inline script, event listener or timeout is entered, you remain completely in control until you return from the end of your block or function.
Upvotes: 0
Reputation: 5648
I'm afraid that's just how alert
works. It's blocking the single thread JavaScript runs on, waiting for an input. I'd suggest alerting in some other fashion. Not only would it be non-blocking, but you could also stylize the actual alert box with CSS.
Upvotes: 4