gpt4 book ai didi

javascript - 一页上有多个 JavaScript 计时器

转载 作者:行者123 更新时间:2023-12-03 07:33:28 26 4
gpt4 key购买 nike

我对javascript了解甚少,希望你们能帮助我。我一遍又一遍地使用同一个计时器,它总是很有魅力。尽管当我尝试在页面下方再次添加相同的计时器时,只有 1 个有效。

function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);

minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;

display.textContent = minutes + ":" + seconds;

if (--timer < 0) {
timer = duration;
}
}, 1000);
}

window.onload = function () {
var fiveMinutes = 60 * 10.1,
display = document.querySelector('.time');
startTimer(fiveMinutes, display);
};
<span class="time">10:07</span>

<br/>
<br/>
<br/>

<span class="time">10:07</span>

我已经尝试为不同的类添加第二个脚本,但不幸的是没有工作结果......

有人能帮帮我吗? JSfiddle 更喜欢,因为我对 javascript 知之甚少!提前致谢!

最佳答案

function startTimer(duration, display, display2) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);

minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;

display.textContent = minutes + ":" + seconds;
display2.textContent = display.textContent;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}




window.onload = function () {
var fiveMinutes = 60 * 10.1,
display = document.querySelector('.time');
display2 = document.querySelector('.time2');
startTimer(fiveMinutes, display ,display2);
};

关于javascript - 一页上有多个 JavaScript 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35719299/

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