首页 > 解决方案 > 如何在“Google Chrome 控制台内部”循环延迟 1 秒

问题描述

我想myCustomFunction 在“Google Chrome 控制台”中运行,每个循环延迟 1 秒

尝试setInterval但无济于事,因为在 Google Chrome 的控制台内没有观察到执行延迟。

const  myCustomFunction = i => console.log('iteration test number', i);
for (let i = 0; i < 11; i++) {
    setInterval(myCustomFunction(i), 1000);
};
  1. 我希望 Google Chrome 的控制台在每次迭代运行之前延迟 1 秒(或更多)myCustomFunction
  2. 我需要它在 Google Chrome 的控制台中工作,而不是在“fileName.js”中的模块

标签: javascriptgoogle-chrome

解决方案


我已经修改了您的代码以提供预期的输出。

const  myCustomFunction = i => console.log('iteration test number', i);
for (let i = 0; i < 11; i++) {
    setTimeout(myCustomFunction, 1000 * i, i);
}

让我们讨论变化,

  1. 替换setIntervalsetTimeout:setInterval在给定的时间间隔内执行给定的函数。因此,如果您调用setInterval(myCustomFunction, 1000),它将myCustomFunction在每 1 秒后重复执行。这不是您想要的行为,您只想要 1 秒的延迟,这setTimeout更合适。
  2. setInterval/的第一个参数setTimeout是一个函数,但myCustomFunction(i)was的输出undefined。所以,不要打电话给myCustomFunction那里,而是通过它。
  3. 将延迟从更改1000i*1000:因为 for 循环的内容执行时没有任何延迟。因此,将延迟更改为在myCustomFunction之后执行i seconds
  4. 的第三个参数setTimeout isetTimeout将第二个(延迟)之后的所有参数传递给回调函数(在我们的例子中myCustomFunction)。

供参考访问

  1. https://developer.mozilla.org/ro/docs/Web/API/window.setTimeout
  2. https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

推荐阅读