gpt4 book ai didi

javascript - 在javascript中有多个倒数计时器事件间隔

转载 作者:行者123 更新时间:2023-11-30 17:20:33 25 4
gpt4 key购买 nike

我正在尝试使用 Javascript 创建多个倒数计时器。面临显示时间和 setInterval cleartInterval Javascript 事件的问题。我的代码在 jsfiddle 上:here

Javascript:

function secondPassed(row, secs) {
var seconds = secs;
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown'+row).innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer[row]);
document.getElementById('countdown'+row).innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}

var countdownTimer = [];

function timer(row, min) {
var seconds = min * 60;
countdownTimer[row] = setInterval('secondPassed('+row+','+seconds+')', 1000);
}


timer(1, 3);
timer(2, 2);
timer(3, 5);

HTML:

Timer 1: <span id="countdown1" class="timer"></span>  
<br/>
Timer 2: <span id="countdown2" class="timer"></span>
<br/>
Timer 3: <span id="countdown3" class="timer"></span>

最佳答案

这里有几个问题。

首先,设置带有参数的定时器函数的语法是错误的。参见 Pass parameters in setInterval function .

其次,您需要将每个计时器的剩余秒数存储在某个地方。

var timerData = [];

function secondPassed(row) {
var seconds = timerData[row].remaining;
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown' + row).innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(timerData[row].timerId);
document.getElementById('countdown' + row).innerHTML = "Buzz Buzz";
} else {
seconds--;
}
timerData[row].remaining = seconds;
}

function timer(row, min) {
timerData[row] = {
remaining: min * 60,
timerId: setInterval(function () { secondPassed(row); }, 1000)
};
}

timer(1, 3);
timer(2, 2);
timer(3, 5);

工作 fiddle :http://jsfiddle.net/835xehna/4/

关于javascript - 在javascript中有多个倒数计时器事件间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25205839/

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