我有一个简单的javascript计数器,计数0到99(代码如下所示)。但是,我不想将setTime
作为每个数字计数增量的时间,而是设置从0到99计算所需的总时间。
var num = 1;
function countUp() {
if (num > 99) {
window.clearTimeout("setTime");
} else {
document.getElementById("the_count").innerHTML = num;
num++;
var setTime = window.setTimeout("countUp()", 1000);
}
}
countUp();
<div id="the_count"></div>
感谢您的帮助。
答案 0 :(得分:2)
试试这个
function countup(start, end, time) {
var i = start;
var interval = setInterval(function() {
if (++i < end) {
document.getElementById("the_count").innerHTML = i;
} else {
clearInterval(interval);
}
}, time / (end - start));
}
countup(0, 100, 5*1000);
&#13;
<div id="the_count"></div>
&#13;
答案 1 :(得分:2)
function countUp (max, time) {
var num = 0;
var step = time / max; // calculate the time between two steps of counting
// create an inner function that performs one step of counting
var fn = function () {
num++;
if (num <= max) {
// if the limit is not reached, display the number ...
document.getElementById("the_count").innerHTML = num;
// ... and call the inner function again, some time in the future
window.setTimeout(fn, step);
}
}
// call the inner function for the first time
fn();
}
countUp(100, 2000); // count up to 100 in 2000ms
<div id="the_count"></div>
答案 2 :(得分:0)
只需使用SetInterval
和ClearInterval
var num = 1;
var setTime = setInterval(countUp, 1000)
function countUp() {
if (num > 99) {
window.clearInterval(setTime);
console.log('stopped')
} else {
document.getElementById("the_count").innerHTML = num;
num++;
}
}
&#13;
<div id="the_count"></div>
&#13;