How to organize an infinite loop (or infinite recursion) in Node.JS without memory leak?

  • 0
    Good afternoon!
    The task is to develop a JavaScript program (in principle) with an unlimited cycle of work using Node.JS. There was a problem that the program eats up memory. The most optimal solution was the following code:
    loop();
    function loop() {
        //Тут произвольный код
        setTimeout(function() {
            loop();
        }, 8);
    }

    But even here there is a leak (0.5 - 1mb per hour) which is extremely critical. The infinite loop solution did not work because it is extremely difficult to organize the delay between iterations without leakage.
    In PHP, the issue is solved simply (if you do not forget to clean the variables in the body of the loop and periodically run forced cleanup) :
    for(;;){
        //Тут произвольный код
        usleep(8000);
    }

    For the first time I ran into the problem of memory leak in JS and couldn't solve the problem on the fly. Probably someone came across a similar one?
    Thank you!
    JavaScript Anonymous, Dec 7, 2019

  • 2 Answers
  • 0
    Solution Lynn Coffeeman ( see comments under the question) helped optimize the program! The first 2-3 hours the situation was worse than with my solution (I suppose by the fact that the code became simpler and the number of iterations per unit of time increased, thereby the speed of memory consumption also increased) , but I do not understand For reasons, after 6-8 hours, memory began to return to the system, and to what extent (the consumed memory was reduced from 6.6mb to 3.4mb) . What happened is not clear. The script works normally. Yes, it still eats up memory, but after a few hours it sharply gives half to the system. There is something to think about.



    For those interested - OS: Ubuntu 18.04.1; platform - Node.JS 8.10; program code:

    loop();
    function loop() {
    setTimeout(loop, 8);
    }




    I'm not sure if the problem won't return. I do not fully understand the nature of all processes. If someone has come across something like this or understands what's going on here (heh) , I'd love to hear your opinion!
    Anonymous

  • 0
    Infinite loop in JS:

    while (true) {
    // do something here
    }




    If we talk about delays, then no one bothers to organize work through (micro) queues and resolve the result through Async / Await.



    BUT!

    According to air-bnb, it is bad practice to resolve async / await in while, forloop loops. Here is the link .



    PS

    There will be leaks, you can't hide from them! Questions about the platform architecture (NodeJS / Browser = & gt; V8) and the garbage collector.
    Felicity Thomas

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!