Advertisements
How to Stop setInterval() Call in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the clearInterval()
Method
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:
Example
Try this code »<!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>
Related FAQ
Here are some more FAQ related to this topic:
- How to call a function after waiting for some time in jQuery
- How to call multiple JavaScript functions in a single onclick event
- How to return multiple values from a function in JavaScript
Advertisements