gpt4 book ai didi

javascript - JS中重置多个定时器

转载 作者:行者123 更新时间:2023-12-01 02:23:08 26 4
gpt4 key购买 nike

我尝试创建一个具有多个计时器的网站。我使用了网站上的脚本。但在此脚本中不可能重置一个计时器或两个计时器。我想从头开始重新启动timer1,所以我必须先重置计时器。如何重置计时器以使用新值启动它?

最后,我想启动Timer1,然后用Timer1的剩余时间+Timer2的新时间启动Timer2。

function countdown(element, minutes, seconds) {
// Fetch the display element
var el = document.getElementById(element);

// Set the timer
var interval = setInterval(function() {
if (seconds == 0) {
if (minutes == 0) {
(el.innerHTML = "STOP!");

clearInterval(interval);
return;
} else {
minutes--;
seconds = 60;
}
}

if (minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}

var second_text = seconds > 1 ? '' : '';
el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + '';
seconds--;
}, 1000);
}

//Start as many timers as you want

var start1 = document.getElementById('timer1');
var start2 = document.getElementById('timer2');

start1.onclick = function() {
countdown('countdown1', 0, 15);
}

start2.onclick = function() {
countdown('countdown2', 0, 10);
}
<html>

<head>
</head>

<body>
<div id='countdown1'></div>
<div id='countdown2'></div>
<input id="timer1" type="button" value="Start timer 1" />
<input id="timer2" type="button" value="Start timer 2" />
</body>

</html>

感谢您的帮助

最佳答案

您可以将间隔作为属性绑定(bind)到元素本身。

  if ( el.interval )
{
clearInterval( el.interval );
}
// Set the timer
var interval = el.interval = setInterval(function() {

演示

function countdown(element, minutes, seconds) {
// Fetch the display element
var el = document.getElementById(element);
if ( el.interval )
{
clearInterval( el.interval );
}
// Set the timer
var interval = el.interval = setInterval(function() {
if (seconds == 0) {
if (minutes == 0) {
(el.innerHTML = "STOP!");

clearInterval(interval);
return;
} else {
minutes--;
seconds = 60;
}
}

if (minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}

var second_text = seconds > 1 ? '' : '';
el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + '';
seconds--;
}, 1000);
}

//Start as many timers as you want

var start1 = document.getElementById('timer1');
var start2 = document.getElementById('timer2');

start1.onclick = function() {
countdown('countdown1', 0, 15);
}

start2.onclick = function() {
countdown('countdown2', 0, 10);
}
<html>

<head>
</head>

<body>
<div id='countdown1'></div>
<div id='countdown2'></div>
<input id="timer1" type="button" value="Start timer 1" />
<input id="timer2" type="button" value="Start timer 2" />
</body>

</html>

关于javascript - JS中重置多个定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49049575/

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