Joji
Joji

Reputation: 5625

Tried to use setTimeout inside a generator to control the process of producing random numbers but failed

I was trying to implement a seeded pseudo-random generator. It will produce random numbers until the time is up. The code is below

function* pseudoRandom(seed) {
  let random = seed;
  let flag = true;
  setTimeout(() => {flag = !flag}, 100); // stop generating after 100ms
  while (flag) {
    random = random * 16807 % 2147483647;
    yield random;
  }
}

let generator = pseudoRandom(1);

console.log([...generator]);

But I still get an error saying FATAL ERROR: invalid array length Allocation failed - JavaScript heap out of memory. I guess the loop didn't stop. So what has gone wrong?

Upvotes: 3

Views: 88

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370789

All the synchronous code in a script will be executed before callbacks get a chance to run. If you have code that blocks (such as endlessly yielding in a while loop without stopping), the callback will never have a chance to run.

For similar reasons, the following code will never exit the while loop:

let flag = false;
setTimeout(() => flag = true);
while (!flag) {
  // do something
}

Check to see if 100ms have passed inside the loop instead:

function* pseudoRandom(seed) {
  let random = seed;
  const start = Date.now();
  while (Date.now() - start < 100) { // stop generating after 100ms
    random = random * 16807 % 2147483647;
    yield random;
  }
}

let generator = pseudoRandom(1);

console.log([...generator].length);

Do note that the number of elements generated in the 100 ms may have a very large range, depending on what else the processor/browser is doing in that time.

Thanks Kaiido, To avoid blocking the visible UI, you could consider moving the blocking part of the script to a worker:

// https://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string
// I put in a Stack Snippet for live demonstration
// in a real project, put this in a separate file
const workerFn = () => {
  function* pseudoRandom(seed) {
    let random = seed;
    const start = Date.now();
    while (Date.now() - start < 100) { // stop generating after 100ms
      random = random * 16807 % 2147483647;
      yield random;
    }
  }
  self.onmessage = ({ data }) => {
    let generator = pseudoRandom(1);
    const arr = [...generator];
    self.postMessage(arr.length);
  };
};
const workerFnStr = `(${workerFn})();`;
const blob = new Blob([workerFnStr], { type: 'text/javascript' });
const worker = new Worker(window.URL.createObjectURL(blob));

worker.onmessage = ({ data: length }) => console.log(length);
worker.postMessage(1234);

Upvotes: 4

Related Questions