i2tutorials

Javascript-SetTimeOut

Javascript-SetTimeOut

 

The setTimeout() method in JavaScript is allowed to execute a function after waiting for the specified time interval. This javascript method returns a numeric value was represents the ID value of the timer.

Unlike the setInterval() method, the setTimeout() method return to executes the function only once. This method can be written with/without the window prefix.

We can use the clearTimeout() method to stop the timeout or to prevent the execution of the function specified in the setTimeout() method. The value returned by the setTimeout() method can be provided as the argument of the clearTimeout() method to cancel the timer.

 

Syntax:

 

window.setTimeout(function, milliseconds);

 

Parameter values:

 

function: Required. The function that will be executed.

milliseconds: Optional. The number of milliseconds to wait before executing the block of code. If omitted, the value 0 is used.

 

 

Example:

 

using the setTimeout() method.

 

<html>
<head>
<title> setTimeout() method </title>
</head>
<body>
<h1> Hello World :) :) </h1>
<h3> This is an example of using the setTimeout() method </h3>
<p> Here, an alert dialog box will display after two seconds. </p>

<script>

var a;

a = setTimeout(fun, 2000);

function fun() {
alert(" Welcome to the I2tutorials.com ");
}
</script>

</body>

</html>

 

OUTPUT:

 

Hello World 🙂 🙂

This is an example of using the setTimeout() method

Here, an alert dialog box will display after two seconds.

 

Example:

 

new tab opens after a time interval of two seconds

 

<html>
<head>
<title> setTimeout() method </title>
</head>
<body>
<h1> Hello World :) :) </h1>
<h3> This is an example of using the setTimeout() method </h3>
<p> Here, a new tab will open after 2 seconds and close after 2 seconds. </p>

<script>
var a = setTimeout(fun1, 2000);
function fun1()
{
var win1 = window.open();
win1.document.write(" <h2> Welcome to the I2tutorials.com </h2>");
setTimeout(function(){win1.close()}, 2000);
}
</script>

</body>

</html>

 

OUPTUT:

 

Hello World 🙂 🙂

This is an example of using the setTimeout() method

Here, a new tab will open after 2 seconds and close after 2 seconds.

 

Example:

 

using the clearTimeout() method

 

<html>
<head>
<title> setTimeout() method </title>
</head>
<body>
<h1> Hello World :) :) </h1>
<h3> This is an example of using the setTimeout() method </h3>
<p> Click the following button before 2 seconds to see the effect. </p>
<button onclick = "stop()"> Stop </button>
<script>
var a = setTimeout(fun1, 2000);
function fun1()
{
var win1 = window.open();
win1.document.write(" <h2> Welcome to the I2tutorials.com </h2>");
setTimeout(function(){win1.close()}, 2000);
}
function stop() {
  clearTimeout(a);
}
</script>

</body>

</html>

 

OUTPUT:

 

Javascript-SetTimeOut

 

Exit mobile version