The clearTimeout() and setTimeout() methods

The clearTimeout() method

The clearTimeout() method is used to cancel a setTimeout() call if you call the clearTimeout() before the time expires from the setTimeout() call.

<body>

<script type="text/javascript" >
function AnnoyingOrange() {
	window.alert("Sign Up to continue!");
}
var GuestMode = window.setTimeout("AnnoyingOrange()",5000);
</script>

<p>If you click the button below within 5 seconds <br>
the Annoying Orange won't disturb you!</p><

<form>
<input type="button" value="Stop the Annoying Orange"
onclick="window.clearTimeout(GuestMode);" />
</form>

</body>

The code adds a button that if it is clicked once it cancels the setTimeout() call so the alert won't pop up.

The setTimeout() method

The setTimeout() method is used to execute a JavaScript function after a certain amount of time has passed. Unlike setInterval() method, the setTimeout() method is executed only once.

function AnnoyingOrange() {
    window.alert("Sign Up to continue!");
}
var GuestMode = window.setTimeout("AnnoyingOrange()",5000);

This code sends the viewer an alert after 5 seconds to sign up in order to continue.
The method is set to the variable GuestMode so we can use it later.

Leave a Reply