EN
TypeScript - make loop with sleep / loop with time intervals
0
points
In this article, we would like to show you how to make a loop with time intervals in TypeScript.
Quick solution:
let i = 0;
const makeIteration = (): void => {
if (i < 5) {
// 5 iterations
console.log(i + 1 + ' / 5');
setTimeout(makeIteration, 500); // 0.5 second waiting
}
i += 1;
};
setTimeout(makeIteration, 500); // 0.5 second waiting
Reusable function example
const makeLoop = (count: number, duration: number, onIteration: (index: number) => void): void => {
let index = 0;
const sleep = duration / count;
const action = function () {
if (index < count) {
onIteration(index++);
setTimeout(action, sleep);
}
};
if (index < count) {
setTimeout(action, sleep);
}
};
// Usage example:
const iterationsCount: number = 5;
const loopDuration: number = 2000; // 2 seconds duration for all loop
makeLoop(iterationsCount, loopDuration, (index) => {
console.log('Iteration: ' + (index + 1) + ' / ' + iterationsCount + '.');
if (index == iterationsCount - 1) {
console.log('Loop finished!');
}
});