Finestra clearInterval()
Esempio
Visualizza l'ora una volta al secondo. Usa clearInterval() per fermare il tempo:
const myInterval = setInterval(myTimer, 1000);
function myTimer() {
const date = new Date();
document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}
function myStopFunction() {
clearInterval(myInterval);
}
Altri esempi di seguito.
Definizione e utilizzo
Il clearInterval()
metodo cancella un timer impostato con il
setInterval()
metodo.
Nota
Per cancellare un intervallo, utilizzare l' id restituito da setInterval():
myInterval = setInterval(function, milliseconds);
Quindi puoi interrompere l'esecuzione chiamando clearInterval():
clearInterval(myInterval);
Guarda anche:
Sintassi
clearInterval(intervalId)
Parametri
Parameter | Description |
intervalId | Required. The interval id returned from setInterval(). |
Valore di ritorno
NESSUNO |
Altri esempi
Alternare tra due colori di sfondo una volta ogni 500 millisecondi:
const myInterval = setInterval(setColor, 500);
function setColor() {
let x = document.body;
x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}
function stopColor() {
clearInterval(myInterval);
}
Usando setInterval() e clearInterval() per creare una barra di avanzamento dinamica:
function move() {
const element = document.getElementById("myBar");
let width = 0;
const id = setInterval(frame, 100);
function frame() {
if (width == 100) {
clearInterval(id);
} else {
width++;
element.style.width = width + '%';
}
}
}
Supporto browser
clearInterval()
è supportato in tutti i browser:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |