Comment sortir de setInterval
-
22-09-2019 - |
Question
Je dois sortir d'un intervalle en cours d'exécution si les conditions sont correctes:
var refreshId = setInterval(function() {
var properID = CheckReload();
if (properID > 0) {
<--- exit from the loop--->
}
}, 10000);
La solution
Utilisez clearInterval :
var refreshId = setInterval(function() {
var properID = CheckReload();
if (properID > 0) {
clearInterval(refreshId);
}
}, 10000);
Autres conseils
Mise à jour pour ES6
Vous pouvez limiter la portée de la variable pour éviter de polluer l'espace de noms:
const CheckReload = (() => {
let counter = - 5;
return () => {
counter++;
return counter;
};
})();
{
const refreshId = setInterval(
() => {
const properID = CheckReload();
console.log(properID);
if (properID > 0) {
clearInterval(refreshId);
}
},
100
);
}
Faire passer la valeur de setInterval
à clearInterval .
Exemple simple
const interval = setInterval(() => {
clearInterval(interval);
}, 1000)
Exemple de compte à rebours
La minuterie est décrémenté chaque seconde, jusqu'à atteindre 0.
let secondsToCountDown = 2
const interval = setInterval(() => {
// just for presentation
document.querySelector('.timer').innerHTML = secondsToCountDown
if (secondsToCountDown === 0) {
clearInterval(interval); // time is up
}
secondsToWait--;
}, 1000);
<p class="timer"></p>
exemple de compte à rebours avec séparation
let secondsToCountDown = 2
const doStuffOnInterval = () => {
document.querySelector('.timer').innerHTML = secondsToCountDown
if (secondsToCountDown === 0) {
stopInterval()
}
secondsToCountDown--;
}
const stopInterval = () => {
clearInterval(interval);
}
const interval = setInterval(doStuffOnInterval, 1000);
<p class="timer"></p>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow