dwib
dwib

Reputation: 595

Is `setInterval` until condition bad practice?

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);

Upvotes: 0

Views: 1510

Answers (2)

Evgenii Klepilin
Evgenii Klepilin

Reputation: 695

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:

Upvotes: 1

Sydney Y
Sydney Y

Reputation: 3152

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!

Upvotes: 0

Related Questions