setInterval
Learn to run code repeatedly at an interval with setInterval.
Repeating call with setInterval
setInterval runs a function repeatedly at a fixed interval. The second parameter is again in milliseconds.
setInterval(() => {
console.log('Tick');
}, 1000);This code logs Tick every second. Unlike setTimeout, the callback is called not once but again and again. The timer keeps running until you stop it with clearInterval. As long as the page is open, the interval repeats forever.
Building a counter with setInterval
Inside setInterval you can increase a variable to build a counter. On each call the variable grows by one and you write the result into an element.
const counter = document.querySelector('#counter');
let count = 0;
setInterval(() => {
count = count + 1;
counter.textContent = count;
}, 1000);This code increases count by one every second and writes it into the #counter element. As long as the page is open, the counter grows forever. To stop it you need clearInterval; we will see it in the next lesson.
Exercise Increase the counter element by 1 every second
Increase a #counter element by 1 every second with setInterval. Increase the count variable and write it to counter.textContent.
Show example solution
const counter = document.querySelector('#counter');
let count = 0;
setInterval(() => {
count = count + 1;
counter.textContent = count;
}, 1000);
Test yourself
-
What is the difference between setInterval and setTimeout?
- setInterval runs the callback repeatedly, setTimeout once
- setInterval is faster
- setTimeout is only for delays
- They are the same
Show answer
setInterval runs the callback repeatedly, setTimeout once — Correct! setInterval calls the callback again and again; setTimeout only once.
-
Complete the setInterval call
setInterval(() => { console.log('Tick'); }, ____);Show answer
setInterval(() => { console.log('Tick'); }, 2000); -
Match the setInterval parts
- setInterval
- repeating timer
- callback
- runs every interval
- 1000
- 1 second interval
- count = count + 1
- increases counter by one