HomeContact
Javascript
Wait until a condition is true in a Javascript function.
July 31, 2020
1 min

Sometime, you will launch a function at a precise time that will not meet the condition (data not yet ready for example), but only some milliseconds later.

To avoid throwing an error and crash an app, it’s possible to use setTimeout to relaunch the function and complete it until a certain condition is true :

function wait(param1, param2) {
  if (!condition) {
    setTimeout(wait, 100, param1, param2)
  } else {
    // CODE to launch until condition is met
  }
}

This function will relaunch until condition is true every 100ms.

Be careful if your function has parameters to pass them AFTER the time parameters in the setTimeout function.

setTimeout(wait(param1, param2), 100);

If you write setTimeout like this it will fill up the Javascript call stack and you’ll get a max call stack error.


Tags

javascript

Related Posts

How to remove space from String using Javascript
February 04, 2021
1 min
© 2023, All Rights Reserved.

Quick Links

Contact Us

Social Media