我想睡觉“计时器”功能,直到有人决定他是否想要在点击“退出”按钮后留下或离开我的网站,这样后台的时间就会被冻结。但如果他决定留下来,计时器功能应该继续。我不知道怎么做。谁能帮助我?感谢您的所有建议。
<!DOCTYPE html>
<html>
<body>
<button onclick="exit();">exit</button>
<p id="seconds">30</p>
<script type="text/javascript">
var clock;
function timer () {
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(30 - (new Date().getTime() - start) / 1000);
if (seconds >= 0)
document.getElementById('seconds').innerHTML = seconds;
else
clearInterval(clock);
if (seconds==0) document.getElementById("fotka").innerHTML='<img src="mopsik.jpg"/>';
}, 1000);
}
function exit(){
var result = confirm("Do you really want to leave this page?");
if (result == true) {
window.location.href="www.something.com";
}
else {
}
}
timer();
</script>
</body>
</html>
答案 0 :(得分:0)
当用户点击退出时,清除间隔(意味着他不再计算秒数),如果结果为假,则再次开始间隔。
var clock;
var start;
function StartTimer () {
if (clock) {
clearInterval(clock);
}
start = new Date().getTime();
startInterval();
}
function startInterval() {
clock = setInterval(function() {
var seconds = Math.round(30 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
document.getElementById('seconds').innerHTML = seconds;
} else{
clearInterval(clock);
}
if (seconds==0)
document.getElementById("fotka").innerHTML='<img src="mopsik.jpg"/>';
}, 1000);
}
function exit() {
clearInterval(clock);
var result = confirm("Do you really want to leave this page?");
if (result == true) {
window.location.href="www.something.com";
} else {
startInterval();
}
}