Ask Your Question
4

How can I program 100 timers with a 100ms interval in typescript to trigger the code execution, if the execution of each timer takes longer than 100ms?

asked 2023-06-02 13:42:28 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-02 13:58:02 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-02 13:42:28 +0000

Seen: 14 times

Last updated: Jun 02 '23