setTimeout in JavaScript | Window setTimeout() Method

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:

Example of setTimeout in JavaScript

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


One thought on “setTimeout in JavaScript | Window setTimeout() Method

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.