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

使用Array forEach()创建元素时如何每隔500ms生成一个div节点

问题原因

你此前使用setTimeout未生效的核心原因是:forEach为同步遍历逻辑,若直接在循环内给所有元素设置固定500ms的延迟,所有定时器会在极短时间内被同步注册完成,最终全部在500ms后同时触发,无法实现间隔创建的效果。

解决方案1:设置递增延迟

利用forEach回调的第二个索引参数,给每个元素的定时器设置依次递增的延迟时间,实现间隔500ms依次创建元素的效果:

var grid = document.getElementById("grid");
const calendar = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
  23, 24, 25, 26, 27, 28, 29, 30,
];
calendar.forEach(myFunction);
function myFunction(value, index) {
  setTimeout(() => {
    let div = document.createElement("div");
    div.classList.add("grid-item");
    div.innerHTML = value;
    grid.appendChild(div);
  }, index * 500)
}

该方案实现逻辑简单,适合数组长度固定的场景。

解决方案2:用setInterval控制遍历节奏

通过定时器控制遍历的进度,遍历完成后自动清除定时器:

var grid = document.getElementById("grid");
const calendar = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
  23, 24, 25, 26, 27, 28, 29, 30,
];
let currentIndex = 0;
const createTimer = setInterval(() => {
  if (currentIndex >= calendar.length) {
    clearInterval(createTimer);
    return;
  }
  let div = document.createElement("div");
  div.classList.add("grid-item");
  div.innerHTML = calendar[currentIndex];
  grid.appendChild(div);
  currentIndex++;
}, 500)

该方案遍历节奏更可控,后续如果需要暂停、提前终止创建逻辑也可以直接操作定时器实现。

内容的提问来源于stack exchange,提问作者Phyo Wai LIn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 06:15:04