JavaScript - setInterval() function example
In this article, we would like to show you how to use setInterval()
in JavaScript.
Quick solution:
xxxxxxxxxx
setInterval(() => {
console.log('This will be displayed every 1000ms (1s).');
}, 1000);
or:
xxxxxxxxxx
const handle = setInterval(() => {
console.log('This will be displayed every 1000ms (1s).');
}, 1000);
clearInterval(handle); // stops intervals
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.
In this example, we create and call a simple function that displays some text every second.
Runnable example:
xxxxxxxxxx
setInterval(() => {
console.log('This will be displayed every 1000ms (1s).');
}, 1000);
In this example, we create a function with setInterval
that counts to 5 every second.
Runnable example:
xxxxxxxxxx
let i = 0;
let interval = setInterval(() => {
console.log(i + 1);
if (++i === 5) {
clearInterval(interval);
}
}, 1000);
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:
xxxxxxxxxx
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);