如何在 for 循环中使用 setInterval 或 setTimeout?
我试图在某些代码运行时设置一个时间间隔,但只需要根据元素的数量来设置。下面是一个简单示例:
总共 5 个元素
对于找到的每个元素,每 20 秒运行一次代码。
有人能给我一个如何使用纯 JavaScript 执行此操作的基本示例吗?我尝试过的所有操作都只是一次执行所有代码,而不是一次执行一个元素。
I am trying to set an interval when some code runs but only need to do it based on the number of elements there are. Here's a quick example:
5 total elements
Run code once every 20 seconds for each element that is found.
Can someone please give me a basic example how to do this using plain JavaScript? Everything I have tried just executes all of the code at once instead of doing one element at a time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设您正在谈论数组或 DOM 集合的元素
编辑:
如果您因任何原因无法反转数组,请使用下一个版本
let's suppose you're talking about elements of an array or a DOM collection
Edit:
if you cannot reverse the array for any reason just use next version
看这个例子: http://juixe .com/techknow/index.php/2005/10/28/put-javascript-to-sleep/
Look at this example: http://juixe.com/techknow/index.php/2005/10/28/put-javascript-to-sleep/
下面是我使用 jQuery 为图像制作动画的一些代码:
技巧是设置一个缓冲区,该缓冲区等于当前动画的索引每个动画所花费的时间。
FOR
循环立即运行每个代码;.delay()
操作和缓冲区变量使得每个动画看起来好像一个接一个地发生。然后,setInterval()
在每个动画完成后调用FOR
循环。它不断地重新启动该过程。Here's some code I did for animating images using jQuery:
The trick was to set a buffer which equaled the time it took for each animation by the index of the current animation. The
FOR
loop runs each code immediately; the.delay()
action and the buffer variable makes it appear as if each animation was happening one after the other. ThensetInterval()
recalls theFOR
loop after every animation is complete. It restarts the process continuously.您必须定义一个函数,并且在函数内部需要为其自身设置超时。像这样:
You have to define a function, and inside the function it needs to set a timeout on itself. Like this: