gpt4 book ai didi

javascript - 如何在一定时间间隔后重复调用函数

转载 作者:行者123 更新时间:2023-11-28 13:01:19 25 4
gpt4 key购买 nike

我正在 JavaScript 中制作一个数字时钟,并尝试使用 setInterval() 每 1000 毫秒刷新一次时钟,但不是每 1000 毫秒后调用函数,而是在重新加载页面后仅调用该函数一次。 1000 毫秒后调用函数的更好方法是什么?

// Getting date method
var currentTime = new Date();
// Assigning variables
var hour = currentTime.getHours();
var min = currentTime.getMinutes();
var sec = currentTime.getSeconds();



// Getting html elements
var hourElement = document.getElementById("hour");
var minELement = document.getElementById("min");
var secElement = document.getElementById("sec");


function setClockTime() {
hourElement.innerHTML = hour;
minELement.innerHTML = min;
secElement.innerHTML = sec;
}


setInterval(setClockTime, 1000);
body {
background: rgb(230, 230, 230);
}

.clock {
display: inline-block;
background: #000;
color: white;
font-size: 10em;
font-family: 'Courier New', Courier, monospace;
padding: 10px;
width: 192px;
text-align: center;
border-radius: 5px;
}

div {
width: 650px;
margin: 0 auto;
}
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>CLOCK</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="normalize.css">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
</head>

<body>

<div class="container">
<p class="clock" id="hour">10</p>
<p class="clock" id="min">20</p>
<p class="clock" id="sec">30</p>
</div>

<script src="s.js"></script>
</body>

</html>

最佳答案

移动要从 setInterval 调用的代码

function setClockTime(){
// Getting date method
var currentTime = new Date();
// Assigning variables
var hour = currentTime.getHours();
var min = currentTime.getMinutes();
var sec = currentTime.getSeconds();
// getting html elements
var hourElement = document.getElementById("hour");
var minELement = document.getElementById("min");
var secElement = document.getElementById("sec");
hourElement.innerHTML = hour;
minELement.innerHTML = min;
secElement.innerHTML = sec;
}

关于javascript - 如何在一定时间间隔后重复调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50175430/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com