【发布时间】:2021-02-17 16:23:09
【问题描述】:
我正在用 JavaScript 制作时钟,其中一部分当然是不断更新时间的 while 循环。我已经搜索了这个错误,它说运行 while 循环会使 JavaScript 无响应。我不知道如何替换 while 循环以及为什么我似乎无法将其放在那里。帮助将不胜感激。这是错误和代码。
var today = new Date();
var hours;
var minutes;
var seconds;
var percentage;
var time;
var clock = document.getElementById("clockHeading");
while (true){
hours = today.getHours();
hours = hours*3600;
minutes = today.getMinutes();
minutes = minutes*60;
seconds = today.getSeconds();
seconds = seconds+minutes+hours;
percentage = seconds/48600;
percentage = String(percentage);
percentage = percentage+"%";
time = document.createTextNode(percentage);
clock.appendChild(time);
}
body{
font-family: "Raleway";
}
#clockHeading{
position: fixed;
top: 50%;
width: 100%;
text-align: center;
font-size: 200px;
}
<!DOCTYPE html>
<html>
<head>
<title>Percent Clock</title>
<link href="style.css" rel="stylesheet">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@300&display=swap" rel="stylesheet">
</head>
<body>
<h1 id="clockHeading"></h1>
<script type="text/javascript" src="clock.js"></script>
</body>
</html>
【问题讨论】:
-
浏览器变得无响应,因为 JS 在单线程上运行并且运行无限循环会阻塞线程。如本文所述stackoverflow.com/questions/38670964/…您可以使用例如
setInterval()
标签: javascript html