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

如何按间隔依次为变量赋值并重复执行100次脚本?

实现重复执行100次并按顺序遍历数组的脚本

你的原代码问题在于:n被固定赋值为数组第一个元素,每次定时器触发都用这个值,所以只会一直输出test1;而且用10秒后停止定时器的逻辑,没法精准控制执行100次。下面给你两种可行的实现方式:

方案一:用setInterval+计数器控制次数

这种方式会按固定间隔执行,同时循环遍历数组元素(数组长度不足时自动从头重复取):

const TestNames = ["test1", "test2", "test3", "test4", "test5"];
let executeCount = 0;
let currentIndex = 0;

const interval = setInterval(() => {
  const Username = TestNames[currentIndex];
  console.log(Username);
  // 这里放你的业务代码
  
  // 更新索引和执行次数
  currentIndex = (currentIndex + 1) % TestNames.length;
  executeCount++;

  // 执行满100次就停止
  if (executeCount >= 100) {
    clearInterval(interval);
  }
}, 2000);

方案二:用for循环+setTimeout精准控制延迟

这种方式能保证每次执行的间隔准确,不会出现定时器堆积的问题:

const TestNames = ["test1", "test2", "test3", "test4", "test5"];
const totalTimes = 100;
const interval = 2000;

for (let i = 0; i < totalTimes; i++) {
  setTimeout(() => {
    const currentIndex = i % TestNames.length;
    const Username = TestNames[currentIndex];
    console.log(Username);
    // 这里放你的业务代码
  }, i * interval);
}

两种方案的区别:

  • 方案一用setInterval,如果你的业务代码执行时间超过2秒,可能会出现执行重叠的情况;
  • 方案二用setTimeout逐个安排执行,每次的执行时间是严格错开的,逻辑更可靠。

内容的提问来源于stack exchange,提问作者Jeffrey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:45:25