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))
}
5
  • You would be better off not using a loop, just use setTimeout or setInterval and keep track. Commented Sep 6, 2019 at 3:47
  • You could also use a closure ? Commented Sep 6, 2019 at 3: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. Commented Sep 6, 2019 at 4: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. Commented Sep 6, 2019 at 4:19
  • Not a duplicate question. This question specifically asked how to pause the delay also. Commented Sep 6, 2019 at 4:56

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Ok , and is it possible to pause the loop? So let's say the loop is running at 2 sec time interval. I pause / resume it using some button.
replace delayAFn with a promise that resolves only when a button is pressed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.