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.
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
Look at this example: http://juixe.com/techknow/index.php/2005/10/28/put-javascript-to-sleep/
You have to define a function, and inside the function it needs to set a timeout on itself. Like this:
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.