0

I know this sounds like a bad idea but is there a way to stop a loop from looping until a condition has been met in javascript.

I'm using underscores .each loop:

foobar.each(function (foo)

Is there way to only loop to the next element when a condition has been met? otherwise wait at the end.

The reason for this is that I'm retrieving data from URL's in the loop. The URL updates on the condition. And unless the loop waits it will renter the loop with the same URL. Therefore, I'll get the same data twice.

T J
  • 42,762
  • 13
  • 83
  • 138
Kieran
  • 612
  • 6
  • 22

1 Answers1

0

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool. Use a plain loop instead. If you are testing the array elements for a predicate and need a Boolean return value, you can use every() or some() instead. If available, the new methods find() or findIndex() can be used for early termination upon true predicates as well.

MDN Link

T J
  • 42,762
  • 13
  • 83
  • 138
sumeet kumar
  • 2,628
  • 1
  • 16
  • 24