我一直在尝试制作倒数计时器,我希望显示剩余时间。但是,当代码运行并且我将其设置为数字(例如5)时,剩下的时间仅为5,所以它不会不断更新。我将如何更新它?
<!DOCTYPE html>
<html>
<head>
<title>Timer</title>
</head>
<body>
<div id="popup-content">
<h6 id=title></h6>
<p>Enter the time(in minutes) you want to spend on this page: </p>
<input type="number" name="quantity" min="1" max="60" id="textBox">
<button onclick="ductivity()" id="set">Set Timer</button> Time Left:
<p id="timeLeft"></p>
</div>
<script>
function ductivity() {
var x = document.getElementById("textBox").value;
var start = Date.now();
var elapsed = (Date.now() - start) / 1000; //time elapsed in seconds
var y = x - elapsed;
if (y >= 0) {
document.getElementById("timeLeft").innerHTML = y;
} else {
document.getElementById("timeLeft").innerHTML = "TIMES UP";
}
}
</script>
</body>
</html>
答案 0 :(得分:1)
使用setInterval()
。查看详细信息here。
答案 1 :(得分:1)
需要一些可以继续执行的功能,而不是一个已完成的功能,因此可以使用setInterval(function(),1000);下面的内容如https://www.w3schools.com/howto/howto_js_countdown.asp
所示<!DOCTYPE html>
<html>
<head>
<title>Timer</title>
</head>
<body>
<div id="popup-content">
<h6 id=title></h6>
<p>Enter the time(in minutes) you want to spend on this page: </p>
<input type="number" name="quantity" min="1" max="60" id="textBox">
<button onclick="ductivity()" id="set">Set Timer</button>
Time Left: <p id="timeLeft"></p>
</div>
<script>
function ductivity(){
let start=Date.now();
let interval = setInterval(function() {
let x = document.getElementById("textBox").value;
let elapsed = (Date.now() - start)/1000;//time elapsed in seconds
let y = Math.floor((x * 60) - elapsed);
if(y>=0){
document.getElementById("timeLeft").innerHTML = "Seconds Left:" + y;
}
else{
document.getElementById("timeLeft").innerHTML = "TIMES UP";
}
},1000);
}
</script>
</body>
</html>