DEV Community

Discussion on: JavaScript: I have a problem to set the conditions of the beginnings of the loops.

Collapse
 
blindfish3 profile image
Ben Calder

From what I can see you have a couple of things you're trying to achieve here:

  1. loop through an array of images
  2. change the index of the looped image array each time the button is pressed

I'd suggest keeping the function that loops through the images separate - especially if it's using setTimeout - and add a separate click-handler function. The click handler can set the appropriate value of n (give this a more meaningful name! - e.g. imagesIndex) and then start the loop function.

I suspect you may have added the confusing/conflicting set of conditions to handle interruption of the loop. You should be able to simplify this if you instead simply stop the loop and start again with updated variables.

In your click handler you could use clearTimeout to stop any currently running loop.

If you post any follow-up questions I'd suggest using a service like jsfiddle, codepen etc. so we can see running code directly ;)