我应该如何在这个 Javascript 实时时钟中使用 setTimeout?
How should I use setTimeout in this Javascript real-time-clock?
我试图做一个实时时钟,但我遇到了问题,setTimeout 不工作,事实上时钟不会自行更新。请问可以帮忙吗?
这是我写的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
var currentDate = new Date();
function startClock() {
time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
setTimeout(startClock, 1000);
}
startClock();
</script>
</body>
</html>
实际上,setTimeout
工作正常,但是您在函数外部实例化 currentDate
,因此它永远不会更新。
这是因为只有在实例化日期时才会捕获时间——它不会自行更新。这意味着如果你只实例化它一次,它只会保留从实例化时开始的时间。
试试这个:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
function startClock() {
var currentDate = new Date();
time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
setTimeout(startClock, 1000);
}
startClock();
</script>
</body>
</html>
使用setTimeout是正确的。
但这不是最佳解决方案。
因为当你调用它自己时它会以指数方式消耗内存。
因此,您可以使用 setInterval 而不是 setTimeout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
function startClock() {
let currentDate = new Date();
time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
}
setInterval(startClock, 1000);
</script>
</body>
</html>
我试图做一个实时时钟,但我遇到了问题,setTimeout 不工作,事实上时钟不会自行更新。请问可以帮忙吗?
这是我写的代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
var currentDate = new Date();
function startClock() {
time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
setTimeout(startClock, 1000);
}
startClock();
</script>
</body>
</html>
实际上,setTimeout
工作正常,但是您在函数外部实例化 currentDate
,因此它永远不会更新。
这是因为只有在实例化日期时才会捕获时间——它不会自行更新。这意味着如果你只实例化它一次,它只会保留从实例化时开始的时间。
试试这个:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
function startClock() {
var currentDate = new Date();
time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
setTimeout(startClock, 1000);
}
startClock();
</script>
</body>
</html>
使用setTimeout是正确的。 但这不是最佳解决方案。 因为当你调用它自己时它会以指数方式消耗内存。
因此,您可以使用 setInterval 而不是 setTimeout:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="p"></p>
<script>
function startClock() {
let currentDate = new Date();
time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();
document.getElementById("p").innerHTML = time;
}
setInterval(startClock, 1000);
</script>
</body>
</html>