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.