Skip to content
Related Articles

Related Articles

Java Script | setTimeout() & setInterval() Method

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 04 Aug, 2022
View Discussion
Improve Article
Save Article

SetTimeout and SetInterval are the only native function in javaScript that is used to run code asynchronously , it means allow the function to executed immediately , there is no need to wait for current execution completion , it will for further to execute.

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

  • 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: 

javascript




<!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

javascript




<!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 1 and above
  •  Edge 12 and above
  • Internet Explorer 4 and above
  • Firefox 1 and above
  • Opera 4 and above
  • Safari 1 and above

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!