pause for loop in javascript

You can pause a for loop in Javascript by adding a conditional statement inside the loop and calling the setTimeout() method. Here's an example:

index.tsx
for (let i = 0; i < 10; i++) {
  // Pause loop at index 5
  if (i === 5) {
    setTimeout(() => {
      console.log('paused for 1 second');
    }, 1000);
  }
  console.log(i);
}
178 chars
10 lines

In this example, the loop will pause when the loop variable i is equal to 5. The setTimeout() method will wait for 1 second before logging the message "paused for 1 second". Once the timeout is complete, the loop will resume and continue to log the remaining values from 6 to 9.

related categories

gistlibby LogSnag