<body onload="count()">
<p id="li1"></p>
<script>
let li1 = document.getElementById("li1");
let x = 0;
function count() {
while(x<=1000){
li1.innerHTML = x++;
}
}
setInterval(count,10)
</script>
</body>
我试着写for而不是使用while,但它也不起作用。
我很快就会重新格式化你的原始帖子。请注意以后的问题格式要正确!
你在提供的代码中做了一些不必要的事情。
首先,您不需要在body
onload
中调用count()
。setInterval
将在DOM加载后运行,并有效地为您处理此问题。
其次,因为您使用setInterval
每10ms运行count()
,所以您不需要任何形式的循环,无论是for
还是while
。setInterval
处理循环(某种程度上)。
看一下以下内容:
// Get the element we want to put the counter inside
let li1 = document.getElementById("li1");
// Init a variable to hold our counter
let x = 0;
// Init a varible to hold our setInterval timer, so we can disable it when conditions are met.
let counterInterval;
//Define our count() function
function count() {
if (x < 1000){
// Set the innerHTML (I'd rather innerText) to x + 1 as long as x is less than 1000
li1.innerHTML = x++;
} else {
// If x is equal to or greater than 1000, clear the timer
clearInterval(counterInterval);
}
}
//Start our interval time to run count() every 10ms and assign it to our counterInterval variable
counterInterval = setInterval(count,10)
<p id="li1"></p>