JavaScript infinite loop and heap memory limit - Fatal error: Heap limit reached Allocation failed - JavaScript heap out of memory
P粉773659687
P粉773659687 2024-03-27 20:21:43
0
1
427

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粉773659687
P粉773659687

reply all(1)
P粉879517403

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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template