B
B
babbert2019-03-16 20:29:30
JavaScript
babbert, 2019-03-16 20:29:30

How to pause a loop?

Is it possible in JS, without using setTimeout, setInterval to accomplish this task:

while(true) {
    open(function() {
        /* async код, который выполняется всегда разное кол. времени */
        cycleContinue()
    });
    cycleSuspend()
}

I know about the existence of promises, I think they can help, but they are somewhat complicated. (An example would be, with such a case.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Shvets, 2019-03-16
@babbert

const randomDelay = () => new Promise(resolve => setTimeout(resolve, Math.random()*1000));

(async function() {
  let counter = 0;
  while (true) {
    console.time('timer');
    await randomDelay();
    console.timeEnd('timer');
    if (counter++ > 20) {
      break;
    }
  }
})();

https://jsfiddle.net/melchiorio/x4dyk197/2/
The randomDelay function runs for an arbitrary amount of time and the whole loop waits for it.
instead of randomDelay there will be your asynchronous function, you need to look at what it is in order to promisify it.

H
hzzzzl, 2019-03-16
@hzzzzl

if it’s paused, then it’s best to rewrite the async code to sync code, of course
you can try

open(async function() {
        /* async код, который выполняется всегда разное кол. времени */
        await myAsyncCode()
        .....
        cycleContinue()
    });

Z
Zukhrullo Moskovskiy, 2019-03-17
@ZaxaCodes

I think that you can also put break, but you will have an exit from the loop, and then you can just call it again

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question