How to call a function repeatedly every 5 seconds in JavaScript ?

The setInterval() method in JavaScript can be used to perform periodic evaluation of expression or call a JavaScript function.

Syntax:

setInterval(function, milliseconds, param1, param2, ...)

Parameters: This function acceps the following parameters:

  • function: Thi sparameter holds the function name which to be called periodically.
  • milliseconds: This parameter holds the period, in milliseconds, setInterval() calls/executes the function above.
  • param1, param2, … : Some additional parameters to be passed as input parameters to function.

Return Value: This method returns the ID representing timer set by the method. This ID can be used to clear/unset the timer by calling clearInterval() method and passing it this ID as a parameter.

Example: Suppose we want to create a reminder timer which goes off every 5 seconds and alerts through a JavaScript alert box.



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to call a function
        repeatedly every 5 
        seconds in JavaScript ?
    </title>
</head>
  
<body>
    <p>
        Click the button to start
        timer, you will be alerted
        every 5 seconds until you
        close the window or press
        the button to stop timer
    </p>
      
    <button onclick="startTimer()">
        Start Timer
    </button>
      
    <button onclick="stopTimer()">
        Stop Timer
    </button>
      
    <script>
        var timer;
          
        function startTimer() {
            timer = setInterval(function() { 
                alert("5 seconds are up"); 
            }, 5000);
        }
          
        function stopTimer() {
            alert("Timer stopped");
            clearInterval(timer); 
        }
    </script>
</body>
  
</html>

chevron_right


Output:

  • Before clicking the button:
  • After clicking the button:

In the above example, the setInterval() method repeatedly evaluates an expression/calls a function. The way to clear/unset the timer set by setInterval() method is to use the clearInterval() method and passing it the ID/value returned on calling setInterval().

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.