The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.
Let's try out the following example to understand how it basically works:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Stop setInterval() Call</title>
</head>
<body>
<p>Press start/stop button to start/stop setInterval() call.</p>
<button type="button" id="startBtn">Start</button>
<button type="button" id="stopBtn">Stop</button>
<div id="myDiv"></div>
<script>
var intervalID;
// Function to call repeatedly
function sayHello(){
document.getElementById("myDiv").innerHTML += '<p>Hello World!</p>';
}
// Function to start setInterval call
function start(){
intervalID = setInterval(sayHello, 1000);
}
// Function to stop setInterval call
function stop(){
clearInterval(intervalID);
}
document.getElementById("startBtn").addEventListener("click", start);
document.getElementById("stopBtn").addEventListener("click", stop);
</script>
</body>
</html>
Use the
clearInterval()MethodThe
setInterval()method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the globalclearInterval()method to cancel or stopsetInterval()call.Let's try out the following example to understand how it basically works:
need an explanation for this answer? contact us directly to get an explanation for this answer