We have seen how to call again and again a function at a time interval by using setInterval() method . Now we will learn how to stop this setInterval by using clearInterval() method in JavaScript. Here is the code
clearInterval(id_of_setInterval)
We have used setInterval() and clearInterval() and developed this code which display the current time on click of Start button and stops displaying on click of Stop button.
DEMO of clearInterval →
Here is the code.
<html>
<head>
<title>Page Title here</title>
<script language=javascript>
function to_start(){
tm=window.setInterval('disp()',1000);
}
function to_stop(){
window.clearInterval(tm);
}
function disp(){
var dt= new Date();
var str=dt.toTimeString()
document.getElementById('n1').value=str;
}
</script>
</head>
<body >
<input type=text id=n1 >
<input type="button" name="btn" value="Start" onclick="to_start()";>
<input type="button" name="btn" value="Stop" onclick="to_stop()";>
</body>
</html>