Wait until a condition is true?

Modern solution using Promise

function waitFor(conditionFunction) {

  const poll = resolve => {
    if(conditionFunction()) resolve();
    else setTimeout(_ => poll(resolve), 400);
  }

  return new Promise(poll);
}

Usage

waitFor(_ => flag === true)
  .then(_ => console.log('the wait is over!'));

or

async function demo() {
  await waitFor(_ => flag === true);
  console.log('the wait is over!');
}

References
Promises
Arrow Functions
Async/Await

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)