Languages
[Edit]
EN

TypeScript - make loop with sleep / loop with time intervals

0 points
Created by:
Rian-Whitehouse
469

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!');
  }
});

Alternative titles

  1. TypeScript - how to make loop with sleep / loop with time intervals?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join