I was asked (by a friend) to build a timer (infinite one which writes a line every second), but without setInterval.
I solved it with :
var i = 0;
function k(myId, cb)
{
setTimeout(function ()
{
console.log(myId);
cb();
}, 1000);
}
function go()
{
i++;
k(i, go);
}
go();
And it is working.
The problem is that I’m afraid there’s gonna be a memory pressure. It actually creates a recursion and after a while (week or something) – the process will consume much memory. (the stack is never deallocated)
How can I change my code in order not to be much memory consume?
It’s not recursion
It may look like recursion, but setTimeout does not create recursion.
The way setTimeout works is that it returns immediately. So the call to
kends immediately with its stack deallocated.When the timeout actually happens and the call to
gohappens again it is not from the point of the previous call tokbut from the global scope*.* Note: I’m not using the strict meaning of scope as defined in ECMAScript spec here. What I mean is the call to
kwill be made as if you have written it in a plain<script></script>tag: that is to say, outside of any other function calls.Regarding your concern over the closure
In your specific case, there is very little that’s actually enclosed in the closure created by the
kfunction. The only significant closure is the reference to the argumentscbandmyId. And even then it only lasts for approximately one second:Could be simpler
I should note that your code is fairly convoluted. It can be written simpler, and without using closures at all (minus the global variable i) if you simply write it like this: