带时间间隔的for循环数据展示:1-100数字延迟显示简易实现
Hey there! I totally get why you're seeing only the last number—regular for loops run super fast. By the time your browser has a chance to update what's on the screen, the loop has already finished iterating through all 100 numbers. Let's fix this with two straightforward, easy-to-understand methods:
Method 1: Use setTimeout with Block-Scoped Variables
This approach leverages let (which creates a new variable for each loop iteration) and setTimeout to add delays between each number display:
const displayElement = document.getElementById('freeRange'); // Loop from 1 to 100 for (let i = 1; i <= 100; i++) { // Delay each update by 100ms * the current number // (Adjust 100 to make the delay shorter/longer) setTimeout(() => { displayElement.textContent = i; }, i * 100); }
How it works:
let iensures each iteration of the loop has its own copy ofi, so when thesetTimeoutcallback runs, it uses the correct number.- The delay (
i * 100) means the first number shows after 100ms, the second after 200ms, and so on until the 100th number shows after 10 seconds.
Method 2: Use setInterval (Even More Intuitive)
If you prefer something that reads like a "count-up timer," setInterval is perfect. It repeats a function at a set interval until we tell it to stop:
const displayElement = document.getElementById('freeRange'); let currentNumber = 1; // Run the function every 100ms const intervalId = setInterval(() => { // Update the display with the current number displayElement.textContent = currentNumber; // Move to the next number currentNumber++; // Stop the timer once we pass 100 if (currentNumber > 100) { clearInterval(intervalId); } }, 100); // Adjust this value to change delay speed
How it works:
- We start with
currentNumber = 1and update the display immediately. - Every 100ms, we increment the number and update the display again.
- When
currentNumbergoes past 100, we callclearIntervalto stop the timer.
Why Your Original for Loop Failed
If you were using something like this:
// ❌ This won't work! const displayElement = document.getElementById('freeRange'); for (var i = 1; i <= 100; i++) { displayElement.textContent = i; }
The loop runs so quickly that the browser doesn't have time to render each number—by the time it catches up, the loop has already finished, so you only see the final value (100).
Either of the two methods above will fix this without any complex tools or libraries!
内容的提问来源于stack exchange,提问作者FuruiTatsu

