0

If i was waiting for a condition to be true before continuing, would it be bad practice or ineffiecient to do this:

const myInterval = setInterval(() => {
  if(condition) {
    doMyAction();
    clearInterval(myInterval);
    return;
  }
}, 1);
dwib
  • 583
  • 4
  • 19

2 Answers2

1

It would all depend on what is the context and your reason to use this approach. If exact timing that you are passing matters, then it would be reasonable to use that. Example of that would be animations. If you need to execute certain animation based on condition and a time interval, then sure, it would definitely work.

In the case when a condition is supplied in no uncertain terms: could take faster, could take longer - then you would definitely want to utilize asynchronous approach. For instance, when you are waiting for a request to be responded from the server, it would all depend on user's internet connection speed, and thus will be different. async/await will definitely be more efficient, and will not waste time or spoil user experience. With setInterval/setTimeout you are gambling on how it's going to play out for users.

In the end of the day, both approaches are useful. You just need to make sure that you make a right choice for any particular problem.

Take a look at usages of async/await in the cases like yours. Here is also another question that discusses similar problem to yours that you can reference.

References:

Evgenii Klepilin
  • 695
  • 1
  • 8
  • 21
0

It's not bad practice, it's actually good practice to end your interval when you can. BUT it's generally not good practice to use intervals to wait for something. JavaScript has built in functionality for that: async/await and Promise. These wait for an asynchronous action like a get request to return an answer before reacting!

Edit: Tips!

  • intervals are for something that is strictly time-based. If you're waiting for a user, try an event listeners.
  • You may be tempted to try a while loop, but they generally don't work well for web because they block any other JavaScript from running until the loop is over!
Sydney Y
  • 2,912
  • 3
  • 9
  • 15
  • 2
    Note that you don't always have the ability to use event listeners. A common example is in a scraper script such as selenium or nightmare.js where you are waiting for someone else's ajax call to complete. You don't have the ability to listen in to that call. So your best bet is to wait for something related to happen (a variable declared, an element to appear etc.). Another common place this can happen is in mashups/widgets. You normally don't have the ability to listen to events directly because you are running in some else's website – slebetman Feb 09 '20 at 06:37