The setTimeout is a method in JavaScript, it used to execute a callback function after the timer expires. The setTimeout() is a method of the window object.
The window object allows execution of code at specified time intervals.
Note: 1000 ms = 1 second.
This function is excused only once but you can repeat execution by using the setInterval() method.
Syntax
setTimeout(function, milliseconds)
Parameter Values
- function– The function that will be executed
- milliseconds: – The number of milliseconds to wait before executing the code.
Example of setTimeout in JavaScript
In the example, an alert box pop up, 2 seconds after the user presses the click me button.
<!DOCTYPE html>
<html>
<body>
<button onclick="setTimeout(timefun, 2000);">
Press me
</button>
<script>
function timefun() {
alert('Welcome to EyeHunts');
}
</script>
</body>
</html>
Output:
Do comment if you have any questions or doubts on this tutorial.
Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version
Thank you! Appreciate these tidbits that make code easier.