Java Script


JavaScript Tutorial


Admission Enquiry Form


setTimeout(), clearTimeout() methods in JavaScript

setTimeout() Method

The setTimeout() method calls a function after a specified number of milliseconds.

setTimeout("demo_compuhelp()", 2000);




Syntax of setTimeout() Method

setTimeout("functioncall",milliseconds)





Example of setTimeout() method

<html>
<head>
<title>Example of setTimeout() method</title>
<script>
function demo_compuhelp()
{
alert("Welcome to Compuhelp");
setTimeout("demo_compuhelp()",2000);
}
</script>
</head>

<body>
<p>Click on the button to wait for 2 seconds, then alert "Welcome to Compuhelp".</p>
<input type="button" value="click" onClick="demo_compuhelp()">
</body>
</html>






clearTimeout() Method

The clearTimeout() method clears a timer set with the setTimeout() method.

The ID value returned by setTimeout() is used as the parameter for the clearTimeout() method.

id=setTimeout("demo_compuhelp()",2000);
clearTimeout(id);





Syntax of clearTimeout() Method

clearTimeout(id of setTimeout method)





Example of clearTimeout() Method

<html>
<head>
<title>Example of clearTimeout() method</title>
<script>
var id;
function demo_compuhelp()
{
alert("Welcome to Compuhelp");
id=setTimeout("demo_compuhelp()",2000);
}

function stop_function()
{
clearTimeout(id);
}
</script>
</head>

<body>
<h2>Click the start button to alert "welcome to compuhelp" after waiting 2 seconds.</h2>

<h2>Click the stop button to prevent the demo_compuhelp() function to execute. (It is must to click it before the 2 seconds are up.)</h2>
<input type="button" value="start" onClick="demo_compuhelp()">&nbsp;&nbsp;
<input type="button" value="stop" onClick="stop_function()">
</body>
</html>