JavaScript - setInterval() function example
In this article, we would like to show you how to use setInterval()
in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
setInterval(() => {
console.log('This will be displayed every 1000ms (1s).');
}, 1000);
or:
// ONLINE-RUNNER:browser;
const handle = setInterval(() => {
console.log('This will be displayed every 1000ms (1s).');
}, 1000);
clearInterval(handle); // stops intervals
Â
1. Documentation
Syntax |
|
Parameters | callback  - function called every indicated time (interval),delay - optional interval time as an integer number (in milliseconds),arg1 , arg2 , arg3 , ... - optional arguments passed as callback arguments. |
Result | Created interval handle (as integer number). |
Description |
|
Â
Below we present some practical examples for better understanding.
1. Simple setInterval
 example
In this example, we create and call a simple function that displays some text every second.
Runnable example:
// ONLINE-RUNNER:browser;
setInterval(() => {
console.log('This will be displayed every 1000ms (1s).');
}, 1000);
2. Calling setInterval
the specified amount of times
In this example, we create a function with setInterval
that counts to 5Â every second.
Runnable example:
// ONLINE-RUNNER:browser;
let i = 0;
let interval = setInterval(() => {
console.log(i + 1);
if (++i === 5) {
clearInterval(interval);
}
}, 1000);
3. Custom setInterval
In this example, we create customSetInterval
that takes in three arguments:
count
- how many times we want to call thecallback
function,delay
- time betweencallback
function calls,callback
- a function to be called.
Runnable example:
// ONLINE-RUNNER:browser;
const customSetInterval = (count, delay, callback) => {
var i = 0;
var interval = setInterval(() => {
callback(i, count);
if (++i === count) {
clearInterval(interval);
}
}, delay);
};
// Usage example:
const foo = (index, count) => console.log(`${index + 1}/${count} Some text here ...`);
customSetInterval(5, 1000, foo);