好的,下面是一个简单的计时器的示例代码。这个计时器可以在页面上显示当前时间,并且每隔 1 秒就会更新一次。
function startTimer() {
// 获取当前时间
const now = new Date();
// 获取当前小时数(0-23)
const hours = now.getHours();
// 获取当前分钟数(0-59)
const minutes = now.getMinutes();
// 获取当前秒数(0-59)
const seconds = now.getSeconds();
// 获取页面中的计时器元素
const timer = document.getElementById('timer');
// 将时间显示在计时器上
timer.innerHTML = `${hours}:${minutes}:${seconds}`;
// 每隔 1 秒就调用 startTimer 函数
setTimeout(startTimer, 1000);
}
// 在页面加载完成后调用 startTimer 函数
window.onload = startTimer;