Window clearInterval() μέθοδος

Ορισμός και χρήση

clearInterval() μεθόδους The setInterval() method θεωρούμενη χρονική διάρκεια.

προειδοποίηση

Για να καθαρίσετε το διαλείμμα, χρησιμοποιήστε setInterval() Επιστρεφόμενος id:

myInterval = setInterval(function, milliseconds);

τότε μπορείτε να καλέσετε clearInterval() για να σταματήσετε την εκτέλεση:

clearInterval(myInterval);

αποτελείτε

The setInterval() method

setTimeout() 方法

clearTimeout() method

Instance

Example 1

Display the time once a second. Use clearInterval() to stop the time:

const myInterval = setInterval(myTimer, 1000);
function myTimer() {
  const date = new Date();
  document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}
function myStopFunction() {
  clearInterval(myInterval);
}

Try it yourself

Example 2

Switch between two background colors every 500 milliseconds:

const myInterval = setInterval(setColor, 500);
function setColor() {
  let x = document.body;
  x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}
function stopColor() {
  clearInterval(myInterval);
}

Try it yourself

Example 3

Create a dynamic progress bar using setInterval() and clearInterval():

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 + '%';
    }
  }
}

Try it yourself

Syntax

clearInterval(intervalId)

Parameters

Parameters Description
intervalId Required. From setInterval() The returned interval id.

Return value

None.

Description

clearInterval() The method stops the specified code from executing periodically, and the operation on these codes is to call The setInterval() method to start. Parameters intervalId must be called The setInterval() method the returned value after.

Browser supports

Όλοι οι περιηγητές υποστηρίζουν clearInterval()

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Υποστήριξη Υποστήριξη Υποστήριξη Υποστήριξη Υποστήριξη Υποστήριξη