Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Java Script | setTimeout() & setInterval() Method

  • Difficulty Level : Basic
  • Last Updated : 26 Jul, 2019

setTimeout() method
The setTimeout() method executes a function, after waiting a specified number of milliseconds.
Syntax:

window.setTimeout(function, milliseconds);

Parameter: There are two parameter that accepted by this method

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

  • function : first parameter is a function to be executed
  • milliseconds : indicates the number of milliseconds before execution takes place.

For example, we want an alert box to pop up, 2 seconds after the user presses the click me button.
Example:




<!DOCTYPE html>
<html>
  
<head>
    <title>
       HTML | DOM Window setTimeout() method
    </title>
</head>
  
<body>
  
    <button onclick="setTimeout(gfg, 2000);">
      Press me
    </button>
  
    <script>
        function gfg() {
            alert('Welcome to GeeksforGeeks');
        }
    </script>
  
</body>
  
</html>

Output:
As soon as the user presses the “press me” button, then after a pause of 2 seconds this message alert
box will pop up.



setInterval() Method
The setInterval() method repeats a given function at every given time-interval.
Syntax:

window.setInterval(function, milliseconds);

Parameter: There are two parameter that accepted by this method

  • function : first parameter is the function to be executed
  • milliseconds :indicates the length of the time-interval between each execution.

Example:




<!DOCTYPE html>
<html>
  
<head>
    <title>
        HTML | DOM Window setTimeout() method
    </title>
</head>
  
<body>
  
    <p>I will say hi many times</p>
  
    <p id="GFG"></p>
  
    <script>
        var myVar = setInterval(myTimer, 1000);
  
        function myTimer() {
            document.getElementById("GFG").innerHTML +=
                                            "<p>Hi</p>";
        }
    </script>
  
</body>
</html>

Output:
After every second a new “hi” message will be displayed.

Then:

Supported Browser: The browser supported by setTimeout() & setInterval() Method are listed nelow:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Opera
  • Safari



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!