2

How would you pause / resume / delay a for loop in Javascript ?

Let's say I have something like this

for (let i = 0; i < 10; i++) {
   console.log('value of i is',i)
}

We can delay an entire function using something like this, but it does not work with a for loop

function delayAFn(ms){
    return new Promise(resolve => setTimeout(() => {
        resolve();
    }, ms))
}
Gaurav_soni
  • 6,064
  • 8
  • 32
  • 49
  • You would be better off not using a loop, just use setTimeout or setInterval and keep track. – epascarello Sep 06 '19 at 03:47
  • You could also use a closure ? – Tejas Sep 06 '19 at 03:56
  • Could you give more context as to why you need the delay? For example, if you want the `for-loop` to go slower, add a nested `for-loop` inside. But if you need to do some async code, then you may need a `Promise`. – ctaleck Sep 06 '19 at 04:07
  • @ChristopherTaleck , I have a data graph, I have the data in an array. But don't want to map the data immediately, the user will be given the option of the speed the data need to be mapped. The user may also pause the execution. Similar to what we do using the browser debugger. – Gaurav_soni Sep 06 '19 at 04:19
  • Not a duplicate question. This question specifically asked how to pause the delay also. – ctaleck Sep 06 '19 at 04:56

2 Answers2

1

What we would have done in the past is a queue type of set up where you use a timeout to call the next iteration if it is still good.

function nextStep(i) {
  console.log(`value of i is ${i}`)
  if (i < 9) {
    window.setTimeout(nextStep, 1000, ++i)
  } else {
    console.log('done')
  }
}
nextStep(0)
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

You can use async/await syntax inside a loop.

for (let i = 0; i < 10; i++) {
   console.log('value of i is',i)
   await delayAFn(1000);
}
William Chong
  • 2,107
  • 13
  • 24