在javascript中有多个倒数计时器事件间隔 [英] Having multiple countdown timer events intervals in javascript
问题描述
我正在尝试使用javascript创建多个倒计时器。
面对显示javascript的时间和setInterval cleartInterval事件的问题。
我的代码在jsfiddle:这里
I am trying to create a multiple countdown timers using javascript. Facing issues with displaying the time and setInterval cleartInterval events of javascript. My code is on jsfiddle: here
Javascript:
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:
计时器1:< span id = countdown1class =timer>< / span>
< br />
计时器2:< span id =countdown2class =timer>< / span>
< br />
计时器3:< span id =countdown3class =timer>< / span>
推荐答案
这里有几个问题。
首先,使用参数设置定时器功能的语法是错误的。请参阅在setInterval函数中传递参数。
First, the syntax for setting a timer function with parameters is wrong. See Pass parameters in setInterval function.
其次,您需要将每个计时器的剩余秒数存储在某处。
Second, you need to store the remaining seconds for each timer somewhere.
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);
工作小提琴: http://jsfiddle.net/835xehna/4/
这篇关于在javascript中有多个倒数计时器事件间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!