gpt4 book ai didi

javascript - 窗口加载时启动计时器

转载 作者:太空宇宙 更新时间:2023-11-04 14:26:04 24 4
gpt4 key购买 nike

我下面有一些代码是一个正向计时器,当我按下 开始 它开始以 hh/mm/ss 计数,当我按下 Display time taken 它显示标签内的 hh/mm/ss 时间,并在单击按钮时将计数器重置为零并从零开始计数。

我的问题是计时器最初只在我按下开始按钮时启动。

我想让计时器在窗口加载时自动启动并删除启动按钮。

如何实现?

window.onload = () => {
let hour = 0;
let minute = 0;
let seconds = 0;
let totalSeconds = 0;

let intervalId = null;

function startTimer() {
++totalSeconds;
hour = Math.floor(totalSeconds / 3600);
minute = Math.floor((totalSeconds - hour * 3600) / 60);
seconds = totalSeconds - (hour * 3600 + minute * 60);

document.getElementById("hour").innerHTML = hour;
document.getElementById("minute").innerHTML = minute;
document.getElementById("seconds").innerHTML = seconds;
}

document.getElementById('start-btn').addEventListener('click', () => {
intervalId = setInterval(startTimer, 1000);
})

document.getElementById('Displplaytimetaken').addEventListener('click', () => {
document.getElementById("timetaken").innerHTML = minute + "minutes" + seconds + "seconds";
reset();
});

function reset() {
totalSeconds = 0;
document.getElementById("hour").innerHTML = '0';
document.getElementById("minute").innerHTML = '0';
document.getElementById("seconds").innerHTML = '0';
}

}
<h1 style="font-size:24px;">Time Taken:
<h1 id="timetaken"></h1>

<button id="start-btn">Start</button>
<button id="Displplaytimetaken">Display time taken</button>

最佳答案

window.onload = () => {
let hour = 0;
let minute = 0;
let seconds = 0;
let totalSeconds = 0;

let intervalId = null;

intervalId = setInterval(startTimer, 1000);
function startTimer() {
++totalSeconds;
hour = Math.floor(totalSeconds / 3600);
minute = Math.floor((totalSeconds - hour * 3600) / 60);
seconds = totalSeconds - (hour * 3600 + minute * 60);

document.getElementById("hour").innerHTML = hour;
document.getElementById("minute").innerHTML = minute;
document.getElementById("seconds").innerHTML = seconds;
}



document.getElementById('Displplaytimetaken').addEventListener('click', () => {
document.getElementById("timetaken").innerHTML = minute + "minutes" + seconds + "seconds";
reset();
});

function reset() {
totalSeconds = 0;
document.getElementById("hour").innerHTML = '0';
document.getElementById("minute").innerHTML = '0';
document.getElementById("seconds").innerHTML = '0';
}

}
<h1 style="font-size:24px;">Time Taken:
<h1 id="timetaken">

</h1>

<h2> <span id="hour"></span>
<span id="minute"></span>
<span id="seconds"></span>
</h2>

<button id="Displplaytimetaken">Display time taken</button>

运行它,希望您的问题得到解决。

关于javascript - 窗口加载时启动计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52912160/

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