Home  >  Q&A  >  body text

JavaScript infinite loop and heap memory limit - Fatal error: Heap limit reached Allocation failed - JavaScript heap out of memory

I'm trying to run some scripts that require a loop to run indefinitely (until a certain condition is met, but this could take forever). The operations inside the loop are very simple, no new variables are created, elements are pushed to the array, or new calls are made. Basically, at least in my opinion, no new resources are used each loop. However, I ended up with the infamous error:

fatal error: reached heap limit allocation failed - javascript heap out of memory

I have been studying memory usage in loops and for simplicity my question can be considered similar to this:

async function main(){
    let n = 5;
    while(1){
        console.log("number: " + n + "; squared: " + n**2);
        console.log(process.memoryUsage());
    }    
}

I found that despite "doing nothing", the heap usage kept growing with each loop. I tried the same turning the loop into a recursive function and got similar results. I'm also familiar with changing the heap memory size allocation, but that's not a solution for this situation as I need it to run indefinitely.

What coding formula should I use to run a loop like this? What should I change to achieve this without increasing the heap? I know something about Garbage Collector and I can assume that it is this feature that is causing the limitation, but can't really understand why. It seems to me that what I'm trying to do is a very simple need that many other people will encounter, and I can't believe Java just disabled it.

Thank you for your answer

P粉773659687P粉773659687205 days ago391

reply all(1)I'll reply

  • P粉879517403

    P粉8795174032024-03-28 18:59:49

    I strongly recommend using setInterval or requestAnimationFrame. JavaScript is single-threaded, which can lead to infinite loops (even within async functions), which may prevent other code from executing.

    I hope this solves your problem.

    let n = 5;
    
    function someFunction() {
      console.log("number: " + n + "; squared: " + n ** 2);
      console.log(process.memoryUsage());
    }
    
    someFunction();
    setInterval(performTask, 1000);

    reply
    0
  • Cancelreply