如何使内联javascript每秒执行一次

yhived7q  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(248)

我有一个内联javascript,它是一个时钟,但时钟不会刷新,这使得它在页面加载的第二秒停止。有人请帮我修一下这个钟。

function showTime() {
  let date = new Date();
  let h = date.getHours(); // 0 - 23
  let m = date.getMinutes(); // 0 - 59
  let s = date.getSeconds(); // 0 - 59
  let session = "AM";

  if (h == 0) {
    h = 12;
  }

  if (h > 12) {
    h = h - 12;
    session = "PM";
  }

  h = (h < 10) ? "0" + h : h;
  m = (m < 10) ? "0" + m : m;
  s = (s < 10) ? "0" + s : s;

  let time = h + ":" + m + ":" + s + " " + session;
  document.getElementById("MyClockDisplay").innerHTML = time;
}
setTimeout(showTime, 1000);
<div id="MyClockDisplay" class="">clock</div>
z31licg0

z31licg01#

setInterval 这就是你想要的。它将在每个时间间隔连续运行,直到您使用clearinterval()手动停止它。因此,您应该为其分配一个变量。

let timeInterval = setInterval(showTime, 1000);
// if ever you want to stop or pause the clock, you can use:
// clearInterval(timeInterval)
function showTime() {
  let date = new Date();
  let h = date.getHours(); // 0 - 23
  let m = date.getMinutes(); // 0 - 59
  let s = date.getSeconds(); // 0 - 59
  let session = "AM";

  if (h == 0) {
    h = 12;
  }

  if (h > 12) {
    h = h - 12;
    session = "PM";
  }

  h = (h < 10) ? "0" + h : h;
  m = (m < 10) ? "0" + m : m;
  s = (s < 10) ? "0" + s : s;

  let time = h + ":" + m + ":" + s + " " + session;
  document.getElementById("MyClockDisplay").innerHTML = time;
}
let timeInterval = setInterval(showTime, 1000);
// if ever you want to stop or pause the clock, you can use:
// clearInterval(timeInterval)
<div id='MyClockDisplay'></div>
elcex8rz

elcex8rz2#

你需要使用 setInterval 而不是
setTimeout setTimeout 在给定的持续时间后仅运行一次。但是 setInterval 将在给定的持续时间内继续运行。只有在 clearInterval 被称为。

相关问题