我在一个页面中有四个计数器我为每个函数调用了单独的函数。我需要将所有函数集成到单个函数中。
var tt1 = setInterval(function() {
startTimee()
}, 50);
var counter1 = 1;
function startTimee() {
if (counter1 == 10) {
clearInterval(tt1);
} else {
counter1++;
}
document.getElementById('counter1').innerHTML = counter1;
}
var tt = setInterval(function() {
startTime()
}, 5);
var counter = 1;
function startTime() {
if (counter == 600) {
clearInterval(tt);
} else {
counter++;
}
document.getElementById('counter2').innerHTML = counter;
}
var tt2 = setInterval(function() {
startTime2()
}, 50);
var counter2 = 1;
function startTime2() {
if (counter2 == 30) {
clearInterval(tt2);
} else {
counter2++;
}
document.getElementById('count3').innerHTML = counter2;
}
var tt3 = setInterval(function() {
startTime3()
}, 50);
var counter3 = 1;
function startTime3() {
if (counter3 == 6) {
clearInterval(tt3);
} else {
counter3++;
}
document.getElementById('counter4').innerHTML = counter3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter1">10</div>
<div id="counter2">600</div>
<div id="counter3">30</div>
<div id="counter4">6</div>
答案 0 :(得分:2)
您可以执行以下操作:
var time = 1, interval = setInterval(tick, 50);
function tick()
{
if (time <= 10)
document.getElementById('counter1').innerHTML = time;
if (time <= 600)
document.getElementById('counter2').innerHTML = time;
if (time <= 30)
document.getElementById('counter3').innerHTML = time;
if (time <= 6)
document.getElementById('counter4').innerHTML = time;
if (++time > 600)
clearInterval(interval);
}
&#13;
<p id="counter1"></p>
<p id="counter2"></p>
<p id="counter3"></p>
<p id="counter4"></p>
&#13;
它不是最优化的代码,但它只是一个例子,你可以得到主要原则。
答案 1 :(得分:2)
根据值的来源,您可以采取几种方法。
第一个选项是创建一个包含span
&#39; id
的对象和要计数的最大值。
var countCeiling = {
counter1: {
end: 10
},
counter2: {
end: 600,
start: 0
},
counter3: {
end: 30,
start: 0
},
counter4: {
end: 6,
start: 0
}
};
var timerID = setInterval(function() {
var stopTimer = true;
for (var id in countCeiling) {
var data = countCeiling[id];
var span = document.getElementById(id);
var val = data.current || data.start || 0;
data.current = val + 1;
if (val <= data.end) {
span.innerHTML = val;
stopTimer = false;
}
}
if (stopTimer) {
clearInterval(timerID);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="counter1">10</div>
<div id="counter2">600</div>
<div id="counter3">30</div>
<div id="counter4">6</div>
&#13;