Java Script | setTimeout() & setInterval() Method

setTimeout() method

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

window.setTimeout(function, milliseconds);

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.



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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);

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

Let us see an example.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Then:

And so on…



My Personal Notes arrow_drop_up

Lets get started

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.