我正在尝试创建一个小型 JavaScript 计时器,其中用户回答问题的时间有限,如果用户没有及时回答,他们将被引导回主页。我从代码中得到的关于计时器的信息实际上就是“[]”。
我的代码:
<DOCTYPE! html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style_q1.css">
<script type="text/javascript">
var time="60";
var min="0";
var sec="0";
function startTimer() {
min=parseInt(timer/60);
sec=parseInt(timer%60);
if(timer<1){
window.location="index.html";
}
document.getElementById("time").innerHTML = "<b> Time Left: </b>"+min.toString()+":"+sec.toString();
timer--;
setTimeout(function(){
startTimer();
}, 1000) ;
}
</script>
</head>
<body onload="startTimer();">
<div id="top">
</div>
<div id="logo">
<h1 style="color:white;"> Question 1 - Geography </h1>
</div>
<div id="game_area">
<center> <h2> What is the capital of Ireland? </h2> </center>
</div>
<div id="time">
<center> <b>[<span id="time" ></span></b>]</center>
</div>
</body>
</html>
最佳答案
只需使用 setInterval()
,它几乎就是为此而设计的:
更新:请记住在时间到时停止 setinterval 过程。
使用此方法clearInterval()
停止该过程。
var secondsLeft = 60;
function startTimer() {
var min=parseInt(secondsLeft/60);
var sec=parseInt(secondsLeft%60);
if(secondsLeft<1){
alert('timer expired');
//window.location="index.html";
}
document.getElementById("time").innerHTML = "<b> Time Left: </b>"+min.toString()+":"+sec.toString();
secondsLeft--;
}
setInterval(startTimer, 1000);
<DOCTYPE! html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style_q1.css">
</head>
<body onload="startTimer();">
<div id="top">
</div>
<div id="logo">
<h1 style="color:white;"> Question 1 - Geography </h1>
</div>
<div id="game_area">
<center> <h2> What is the capital of Ireland? </h2> </center>
</div>
<div id="time">
<center> <b>[<span id="time" ></span></b>]</center>
</div>
</body>
</html>
关于javascript - 我的 JavaScript 计时器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48308080/