【问题标题】:Page Unresponsive when running while loop javascript运行while循环javascript时页面无响应
【发布时间】: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>

【问题讨论】:

标签: javascript html


【解决方案1】:

while(true) 会持续运行,阻塞主线程。如果您需要它连续运行一个时钟,最好使用setInterval 或递归setTimeout

setInterval(() => {
  // Your code
}, 1000)

或:

function timer() {
  setTimeout(() => {
    // Your code

    timer()
  }, 1000)
}

timer()

查看this post了解它们之间的区别。


示例:

var clock = document.getElementById("clockHeading");

setInterval(() => {
  var today = new Date();
  var hours = today.getHours() * 3600;
  var minutes = today.getMinutes() * 60;
  var seconds = today.getSeconds() + minutes + hours;
  var percentage = String(seconds / 48600) + '%';

  clock.innerHTML = percentage;
}, 1000)
body {
  font-family: "Raleway";
}

#clockHeading {
  position: fixed;
  top: 50%;
  width: 100%;
  text-align: center;
  font-size: 20px;
}
<link href="https://fonts.googleapis.com/css2?family=Raleway:wght@300&display=swap" rel="stylesheet">

<h1 id="clockHeading"></h1>

【讨论】:

    猜你喜欢
    • 2011-10-22
    • 2021-12-23
    • 1970-01-01
    • 2018-10-17
    • 2018-12-10
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多