Js render, which is interrupted after the condition is met

How to set setInterval rendering cycle, which is interrupted after the condition is met?

+5
source share
4 answers

You can save the interval id and clear it with clearInterval()for example

var timer = setInterval(myFunction, 1000);

function myFunction() {
  if(condition) {
    clearInterval(timer);
    return;
  }
  //do stuff
}

Or, if you can just call clearInterval()where you set the condition, so the next interval does not start without having any logic in the function itself.

+8
source

clearIntervalstops repeating with setIntervalusing the identifier returned setInterval:

var interval = setInterval(function() {
    // do your loop
    if (loop_should_stop) {
        clearInterval(interval);
    }
}, dt);
+4
source

, , setInterval(), clearInteval(). setInterval :

var int=self.setInterval("your_function_name()",1000);
if(condition){
    clearInterval(int)
}
0

Nick answers 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 call it like that

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

    });
0
source

All Articles