The clearInterval() method

The clearInterval() method is used to end the annoying alerts from the code of the previous post.

window.clearInterval(name);

Before working with the clearInterval() method you have to assign your setInterval() call to a variable.

<script type="text/javascript" >
function AnnoyingOrange() {
	window.alert("I am an annoying orange!");
}
var CrazyAlerts = window.setInterval("AnnoyingOrange()",5000);
</script>

Now we can you clearInterval() method by calling it with the CrazyAlerts as a parameter. We can place a button which the viewer can press to stop interval from running.

<body>

<p>An alert will pop up every 5 seconds</p>

<script type="text/javascript" >
function AnnoyingOrange() {
	window.alert("I am an annoying orange!");
}
var CrazyAlerts = window.setInterval("AnnoyingOrange()",5000);
</script>

<p>You can click the button below<br> to stop the alerts from popping up.</p>

<form>
<input type="button" value="Stop the alerts" 
onclick="window.clearInterval(CrazyAlerts);" />
</form>

</body>

Of course, these alerts are quite useless but the setInterval() and clearInterval() methods are usually used for things that have to be updated regularly (clocks for example).

Leave a Reply