Open In App

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

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:  



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().






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


Article Tags :