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.

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

6 Comments

Wouldn't a normal loop cause the same problem. I don't need to break or stop entirely. I need a pause. And it needs to perform every loop. Just at the right time.
then you need some kind of generator function.. which pauses or yields as per your call
Okay, thank you. I think logic in the duplicate posted at the top will work. I'll look into both ways though.
I looked into generator functions. They seem to be exactly what I need thank you.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.