How to call a function repeatedly every 5 seconds in JavaScript ?
Last Updated :
06 Mar, 2024
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 ?
Share your thoughts in the comments
Please Login to comment...