javascript - 如何在“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);
};
- 我希望 Google Chrome 的控制台在每次迭代运行之前延迟 1 秒(或更多)
myCustomFunction
。 - 我需要它在 Google Chrome 的控制台中工作,而不是在“fileName.js”中的模块
解决方案
我已经修改了您的代码以提供预期的输出。
const myCustomFunction = i => console.log('iteration test number', i);
for (let i = 0; i < 11; i++) {
setTimeout(myCustomFunction, 1000 * i, i);
}
让我们讨论变化,
- 替换
setInterval
为setTimeout
:setInterval
在给定的时间间隔内执行给定的函数。因此,如果您调用setInterval(myCustomFunction, 1000)
,它将myCustomFunction
在每 1 秒后重复执行。这不是您想要的行为,您只想要 1 秒的延迟,这setTimeout
更合适。 setInterval
/的第一个参数setTimeout
是一个函数,但myCustomFunction(i)
was的输出undefined
。所以,不要打电话给myCustomFunction
那里,而是通过它。- 将延迟从更改
1000
为i*1000
:因为 for 循环的内容执行时没有任何延迟。因此,将延迟更改为在myCustomFunction
之后执行i seconds
。 - 的第三个参数
setTimeout
i
:setTimeout
将第二个(延迟)之后的所有参数传递给回调函数(在我们的例子中myCustomFunction
)。
供参考访问
推荐阅读
- mysql - SQL prepared statements
- macos - Mac OS 调整大小按钮
- macos - 管理团队的计算机
- objective-c - 在 iPhone 上使用 Actionsheet 选择器获取文本输入弹出对话框的简单方法是什么
- spring-boot - 如何使 spring security 授权用户类型仅访问某些控制器功能?
- c++ - 错误:类型的无效操作数'
' 和 'int' 到二进制 'operator>' if(min > max) - docker - 在 Docker 容器中安装 node_modules 并与主机同步
- visual-studio - Windbg 内核调试器显示在 VS2015 和 VS2017 中编译的 C++ x64 应用程序的错误用户模式堆栈
- python - 使用 OpenCV 从图像中识别地标和裁剪嘴的脚本看不到人脸
- r - Shiny - observeEvent 无需点击即可出现