这是我的片段。
$(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>
只需尝试重新加载页面。您会收到警报。在那个警报期间,我的计时器没有运行。所以用户可以作弊测试。如何解决这个问题?
最佳答案
恐怕这就是 alert
的工作原理。它阻塞了运行 JavaScript 的单线程,等待输入。我建议以其他方式提醒。它不仅是非阻塞的,而且您还可以使用 CSS 对实际的警告框进行样式化。
关于javascript - 显示警报时在后台运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35556925/