Bootcamp
Search…
1.7: setInterval

Introduction

setInterval repeats a callback function indefinitely at a designated interval until stopped.

Infinite Example

1
console.log('starting...');
2
​
3
const delayInMilliseconds = 1000; // this is one second
4
​
5
const ref = setInterval(() => {
6
console.log(`I happen after ${delayInMilliseconds}`);
7
}, delayInMilliseconds);
8
​
9
console.log('bananas!');
Copied!

Example that Stops

1
console.log('starting...');
2
​
3
const delayInMilliseconds = 1000; // this is one second
4
let counter = 0;
5
​
6
const ref = setInterval(() => {
7
console.log(`I happen after ${delayInMilliseconds}`);
8
console.log(counter);
9
counter += 1;
10
​
11
if (counter > 10) {
12
clearInterval(ref);
13
}
14
}, delayInMilliseconds);
15
​
16
console.log('bananas!');
Copied!

Exercise

Run the above code.