How do I set up a setInterval render loop that breaks, once a开发者_StackOverflow社区 condition is met?
You can store the interval ID and clear it via 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 setting the condition, so the next interval doesn't run, having no logic for this in the function itself.
clearInterval
stops the repetition from setInterval
, using the ID returned by setInterval
:
var interval = setInterval(function() {
// do your loop
if (loop_should_stop) {
clearInterval(interval);
}
}, dt);
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 () {
...
...
});
});
If you ask on how to stop a function call that has been set using setInterval(), just use the clearInteval() function. You first have to save a reference to the setInterval function and than use this reference to stop the interval:
var int=self.setInterval("your_function_name()",1000);
if(condition){
clearInterval(int)
}
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
精彩评论