Open In App

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

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

to call a function repeatedly every 5 seconds in JavaScript we can use the setInterval() method perform periodic evaluations of expressions or call a function. 

Syntax: 

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

Parameters: This function accepts the following parameters:  

  • function: This parameter 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 the timer set by the method. This ID can be used to clear/unset the timer by calling the clearInterval() method and passing it to this ID as a parameter.

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

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</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>
 
    <p id="gfg"></p>
    <script>
        let timer;
 
        function startTimer() {
            timer = setInterval(function () {
                document.getElementById('gfg')
                    .innerHTML = " 5 seconds are up ";
            }, 5000);
        }
 
        function stopTimer() {
            document.getElementById('gfg')
                .innerHTML = " Timer stopped ";
            clearInterval(timer);
        }
    </script>
</body>
 
</html>


Output:  

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

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads