Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use setTimeout to create a cheap infinite loop?

var recurse = function(steps, data, delay) {
    if(steps == 0) {
        console.log(data.length)
    } else {
        setTimeout(function(){
            recurse(steps - 1, data, delay);
        }, delay);
    }
};

var myData = "abc";
recurse(8000, myData, 1);

What troubles me with this code is that I'm passing a string on 8000 times. Does this result in any kind of memory problem?

Also, If I run this code with node.js, it prints immediately, which is not what I would expect.

like image 993
Steinbitglis Avatar asked Dec 27 '22 15:12

Steinbitglis


2 Answers

If you're worried about the string being copied 8,000 times, don't be, there's only one copy of the string; what gets passed around is a reference.

The bigger question is whether the object created when you call a function (called the "variable binding object" of the "execution context") is retained, because you're creating a closure, and which has a reference to the variable object for the context and thus keeps it in memory as long as the closure is still referenced somewhere.

And the answer is: Yes, but only until the timer fires, because once it does nothing is referencing the closure anymore and so the garbage collector can reclaim them both. So you won't have 8,000 of them outstanding, just one or two. Of course, when and how the GC runs is up to the implementation.

Curiously, just earlier today we had another question on a very similar topic; see my answer there as well.

like image 185
T.J. Crowder Avatar answered Jan 17 '23 18:01

T.J. Crowder


It prints immediately because the program executes "immediately". On my Intel i5 machine, the whole operation takes 0.07s, according to time node test.js.

For the memory problems, and wether this is a "cheap infinite loop", you'll just have to experiment and measure.

If you want to create an asynchronous loop in node, you could use process.nextTick. It will be faster than setTimeout(func, 1).

like image 25
August Lilleaas Avatar answered Jan 17 '23 17:01

August Lilleaas