JavaScript setTimeout() Method
You are Here:
JavaScript setTimeout() Method
The setTimeout()
method starts a timer that executes a piece of code after the specified number of milliseconds have elapsed.
Note: Unlike setInterval(), the setTimeout()
method will execute a function only once, after a specified number of milliseconds.
The following example will call the function (myFunction()) after 3 seconds.
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<p>Click the button and wait for 3 seconds.</p>
<button onclick="myFunction()">Click Me</button>
<script>
function myFunction(){
setTimeout(myDisplay, 3000)
}
function myDisplay(){
alert("I'm 3 seconds delay");
}
</script>
</body>
</html>
Syntax
setTimeout(function, delay, param1, ..., paramN);
//or
setTimeout(function, delay);
Parameter Values
Value | Type | Explanation |
---|---|---|
function | Required | Specifies a function to be executed. |
delay | Optional | Specifies a time delay in millisecond. If omitted, the default value is 0. Note: 1000ms = 1sec. |
param1, ..., paramN | Optional | Specifies the additional parameters to pass to the function. Param is not supported in IE9 and earlier. |
setTimeout() with Self Function
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<p>Click the button and wait for 3 seconds.</p>
<button onclick="myFunction()">Click Me</button>
<script>
function myFunction(){
setTimeout(function(){
alert("I'm 3 seconds delay");
}, 3000)
}
</script>
</body>
</html>
setTimeout() with Optional Parameter
Example
HTML Online Editor
<!DOCTYPE html>
<html>
<body>
<p>Click the button</p>
<button onclick="myFunction()">Click Me</button>
<script>
function myFunction(){
setTimeout(myDisplay , 3000, sayHello())
}
function myDisplay(){
alert("I'm 3 seconds delay");
}
function sayHello(){
alert("Hello");
}
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in JavaScript.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.