How to delay a loop in a generator function in JavaScript?

I wrote a small generator that simply lists a bunch of messages that I passed to him:

'use strict';

const sequential = function * (messages) {
  for (let i = 0; i < messages.length; i++) {
    yield messages[i];
  }
};

module.exports = sequential;

I use it as follows:

for (const message of sequential(messages)) {
  // Do something to message...
}

Basically, everything is working fine. Now I want the generator to delay calls yield, for example. for 100 milliseconds.

The problem is that I cannot just enter a call setTimeout, because otherwise it is yieldno longer contained in the generator function, but a regular callback.

How can i solve this?

+4
source share
1 answer

, - , , . , . , . , , , .

+4

Source: https://habr.com/ru/post/1609815/


All Articles