TypeScript - setInterval() function example
In this article, we would like to show you how to use setInterval() in TypeScript.
Quick solution:
setInterval((): void => {
console.log('This will be displayed every 1000ms (1s).');
}, 1000);
or:
const handle = setInterval((): void => {
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:
setInterval((): void => {
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:
let i = 0;
const interval = setInterval((): void => {
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 thecallbackfunction,delay- time betweencallbackfunction calls,callback- a function to be called.
Runnable example:
const customSetInterval = (count: number, delay: number, callback: (i: number, count: number) => void): void => {
let i = 0;
const interval = setInterval(() => {
callback(i, count);
if (++i === count) {
clearInterval(interval);
}
}, delay);
};
// Usage example:
const foo = (index: number, count: number): void => console.log(`${index + 1}/${count} Some text here ...`);
customSetInterval(5, 1000, foo);
Output (one line every second):
1/5 Some text here ...
2/5 Some text here ...
3/5 Some text here ...
4/5 Some text here ...
5/5 Some text here ...