JavaScript setInterval()
JavaScript’s setInterval() is a built-in function that belongs to the Window object. It repeatedly calls a function or executes a code snippet at specified time intervals, creating a continuous loop of execution until it is explicitly stopped.
Syntax
setInterval(func, delay)
setInterval(func, delay, arg1)
setInterval(func, delay, arg1, arg2)
setInterval(func, delay, arg1, arg2, /* … ,*/ argN)
Parameters:
func: A function to be executed everydelaymilliseconds. The first execution happens afterdelaymilliseconds.delay: The time, in milliseconds, between each execution of the specified function. Defaults to 0 if not specified.arg1, ..., argN(optional): Additional arguments passed to the function specified byfunconce the timer expires.
Return value:
The setInterval() method returns a positive integer (interval ID) that uniquely identifies the timer created by the call. This identifier can be passed to clearInterval() to cancel the interval.
Example 1: Basic Counter Using setInterval()
This example demonstrates a simple counter that increments every second and displays the count in the console:
let count = 0;// Function to increment and display countfunction incrementCounter() {count++;console.log(`Count: ${count}`);}// Set interval to call incrementCounter every 1000ms (1 second)const intervalId = setInterval(incrementCounter, 1000);// Stop the counter after 5 secondssetTimeout(() => {clearInterval(intervalId);console.log('Counter stopped');}, 5000);
This example results in the following output:
Count: 1Count: 2Count: 3Count: 4Count: 5Counter stopped
Example 2: Real-time Clock Display Using setInterval()
This example creates a real-time digital clock that updates every second and displays the current time in a webpage element:
<!DOCTYPE html><html><head><title>Real-time Clock</title></head><body><h1>Digital Clock</h1><div id="clock">Loading...</div><button onclick="stopClock()">Stop Clock</button><script>// JavaScript code goes here</script></body></html>
// Function to update the clock displayfunction updateClock() {const now = new Date();const timeString = now.toLocaleTimeString();// Update the clock element with current timeconst clockElement = document.getElementById('clock');if (clockElement) {clockElement.textContent = timeString;}}// Update clock immediatelyupdateClock();// Set interval to update clock every secondconst clockInterval = setInterval(updateClock, 1000);// Function to stop the clockfunction stopClock() {clearInterval(clockInterval);console.log('Clock stopped');}
This example results in the following output:
Clock displays: 2:30:45 PMClock displays: 2:30:46 PMClock displays: 2:30:47 PM(continues updating every second)
Example 3: Using setInterval() to Auto-refresh Data Feed
This example demonstrates fetching and displaying data from an API at regular intervals, simulating a real-time data feed:
let updateCount = 0;const maxUpdates = 10;// Function to fetch and display dataasync function fetchDataFeed() {try {updateCount++;console.log(`Fetching data update #${updateCount}`);// Simulate API call with random dataconst mockData = {timestamp: new Date().toISOString(),temperature: Math.round(Math.random() * 30 + 10),humidity: Math.round(Math.random() * 50 + 30),};// Display the dataconsole.log(`Temperature: ${mockData.temperature}°C`);console.log(`Humidity: ${mockData.humidity}%`);console.log(`Last updated: ${mockData.timestamp}`);console.log('---');// Stop after maximum updatesif (updateCount >= maxUpdates) {clearInterval(dataFeedInterval);console.log('Data feed stopped');}} catch (error) {console.error('Error fetching data:', error);}}// Set interval to fetch data every 3 secondsconst dataFeedInterval = setInterval(fetchDataFeed, 3000);// Initial data fetchfetchDataFeed();
This example results in the following output:
Fetching data update #1Temperature: 23°CHumidity: 45%Last updated: 2024-01-15T10:30:00.000Z---Fetching data update #2Temperature: 27°CHumidity: 38%Last updated: 2024-01-15T10:30:03.000Z---(continues for 10 updates, then stops)
Note: Since this example generates random temperature and humidity values and uses the current timestamp, the actual output will vary each time the code runs. The values shown above are sample outputs for demonstration purposes.
Frequently Asked Questions
1. What happens if I don’t call clearInterval()?
The interval will continue running indefinitely until the page is refreshed or closed, which can cause memory leaks and performance issues.
2. Can I use setInterval() with arrow functions?
Yes, setInterval() works with arrow functions, regular functions, and anonymous functions.
3. What’s the difference between setInterval() and setTimeout()?
setInterval() executes repeatedly at specified intervals, while setTimeout() executes only once after a specified delay.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
- Includes 34 Courses
- With Professional Certification
- Beginner Friendly.115 hours
- Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
- Beginner Friendly.15 hours