js render loop that breaks once a condition is met

Viewed 12067

How do I set up a setInterval render loop that breaks, once a condition is met?

5 Answers

Nick's answer works perfectly. I extended it by returning a promise

function checkUntil(conditionFunc, millisecondsInterval) {
    var retryCount = 0;
    var retryCountLimit = 100;

    var promise = new Promise((resolve, reject) => {
        var timer = setInterval(function () {
            if (conditionFunc()) {
                clearInterval(timer);
                resolve();
                return;
            }
            retryCount++;
            if (retryCount >= retryCountLimit) {
                clearInterval(timer);
                reject("retry count exceeded");
            }
        }, millisecondsInterval);
    });

    return promise;
}

and you can invoke it like so

checkUntil(function () {
        return document.querySelector('body');
    }, 500).then(function () {
          ...
          ...
        });

    });

Improving on @aTable 's answer using 2022 Javascript:

function waitUntil(conditionFunction, millisecondsInterval) {
  const retryCountLimit = 10;
  let retryCount = 0;

  return new Promise((resolve, reject) => {
    const timer = setInterval(() => {
      if (conditionFunction()) {
        clearInterval(timer);
        resolve();
      }

      retryCount++;

      if (retryCount >= retryCountLimit) {
        clearInterval(timer);
        reject(new Error('WaitUntil() retry count exceeded'));
      }
    }, millisecondsInterval);
  });
}

And it can be invoked with:

await waitUntil(document.getElementById('SOME_ID'), 500);

// do stuff
Related