You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带时间间隔的for循环数据展示:1-100数字延迟显示简易实现

Fix: Display Numbers 1 to 100 with Delay (No Fancy Tech Needed)

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 i ensures each iteration of the loop has its own copy of i, so when the setTimeout callback 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 = 1 and update the display immediately.
  • Every 100ms, we increment the number and update the display again.
  • When currentNumber goes past 100, we call clearInterval to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:36:05