Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to call a function repeatedly every 5 seconds in JavaScript?
In JavaScript, setInterval() allows you to execute a function repeatedly at specified time intervals. To call a function every 5 seconds, you pass the function and 5000 milliseconds as arguments.
Syntax
setInterval(function, delay);
Where function is the function to execute and delay is the time in milliseconds between executions.
Basic Example
function myFunction() {
console.log("Function called at:", new Date().toLocaleTimeString());
}
// Call myFunction every 5 seconds (5000 milliseconds)
setInterval(myFunction, 5000);
Function called at: 2:30:15 PM Function called at: 2:30:20 PM Function called at: 2:30:25 PM
Using Arrow Functions
You can also use arrow functions for more concise syntax:
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Execution #${count} at ${new Date().toLocaleTimeString()}`);
}, 5000);
Execution #1 at 2:30:15 PM Execution #2 at 2:30:20 PM Execution #3 at 2:30:25 PM
Stopping the Interval
setInterval() returns a unique ID that you can use with clearInterval() to stop the repeated execution:
let counter = 0;
const intervalId = setInterval(() => {
counter++;
console.log(`Count: ${counter}`);
// Stop after 3 executions
if (counter === 3) {
clearInterval(intervalId);
console.log("Interval stopped");
}
}, 5000);
Count: 1 Count: 2 Count: 3 Interval stopped
Key Points
setInterval()continues executing until cleared withclearInterval()or the page is closedThe delay is specified in milliseconds (5000ms = 5 seconds)
Always store the returned ID if you plan to stop the interval later
The function executes asynchronously without blocking other code
Browser Example with DOM
<!DOCTYPE html>
<html>
<head>
<title>setInterval Demo</title>
</head>
<body>
<div id="timer">Timer will appear here</div>
<button onclick="stopTimer()">Stop Timer</button>
<script>
let seconds = 0;
const intervalId = setInterval(() => {
seconds += 5;
document.getElementById('timer').innerHTML = `Elapsed: ${seconds} seconds`;
}, 5000);
function stopTimer() {
clearInterval(intervalId);
document.getElementById('timer').innerHTML = 'Timer stopped';
}
</script>
</body>
</html>
Conclusion
setInterval() is the standard way to repeatedly execute functions at fixed intervals. Remember to use clearInterval() when you need to stop the execution to prevent memory leaks.
