Ask Your Question

Revision history [back]

One option would be to use a recursive function that triggers the next timer after the previous one has completed its execution. This can be achieved using a combination of setTimeout() and Promises.

Here's an example code snippet in TypeScript to achieve this:

const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

let i = 0;

const executeTimer = async () => {
  // Wait for previous timer to complete before executing the next one
  await delay(100);

  // Execute code here
  console.log(`Timer ${i++} executed`);

  // Trigger the next timer
  executeTimer();
};

// Start the first timer
executeTimer();

In this example, the executeTimer() function uses await to wait for the previous timer to complete before executing the next one. The delay() function returns a Promise that resolves after the specified number of milliseconds using setTimeout(). This ensures that each timer has a fixed interval of 100ms between them.

Note that this approach relies on the assumption that the execution time of the code inside each timer is less than 100ms. If the code takes longer than 100ms to execute, the timers will start to stack up and the overall execution time will increase accordingly.