Search code examples
javascriptperformanceheap-memory

JavaScript infinite loops and Heap memory limit - fatal error: reached heap limit allocation failed - javascript heap out of memory


I am 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 within the loop are very simple and do not create new variables, push elements to arrays or make new calls. Basically, no new resources are used on every loop, at least as far as I see it. However, I end up getting the infamous error:

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

I have been investigating memory usage in loops and for the sake of simplicity of my question, mine can be considered analogue to this:

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

I found that the heap usage keeps growing on every loop despite "nothing" being made. I tried this same turning the loop into a recursive function with similar results. I am also familiar with changing the heap memory size allocation but that is not a solution for this case since I need this to run indefinitely.

What coding formulation should I use to run a loop like this? What should I change to make this possible without the heap growing? I know a bit about the garbage collector and I can figure it is this feature what is causing the limitation but cannot really understand why. This thing I want to do seems to me a pretty straightforward need that many other people will have come across with and I cannot believe Java has just disabled it like this.

Thanks for your answers


Solution

  • I would strongly suggest to use setInterval or requestAnimationFrame. JavaScript is single-threaded, which may cause infinite loops (even in async functions) to potentially block the execution of other code.

    I hope this will fix your issue.

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