EDIT: This is just a simple example to demontrate the concern I have with a much larger program. I wouldn\'t use this actual code for anything :)
If I r
A new closure is created every time the timeout callback is called, as you correctly say. But once the callback has been executed, there is no longer anything referencing the previous closure, so it can be garbage collected.
In my understanding, when a closure is created, the current lexical context is bundled with it. In your case, it would be the amount, win, data
.
This context will be used, when the timeout fires, to execute the closure and thus call once again the function update
; this call, although it might appear so, is not recursive, because the previous execution of update
already ended and its original context (dynamic, which is different from the lexical one) has already been freed. (I think this is important to notice, because it seems you are worrying about a sort of stack growth due to recursion).
So, again, update
is executed a second time and again a timeout is set and a closure created. This closure is bundled with the current lexical context of execution (which still includes just amount, win, data
) and scheduled with the timer. then update
finishes and removed from the stack. then again the timer fires and update is called again...
So, you should not worry about an unlimited growth of the context, for two reasons: first, only the lexical context is bundled with the closure; the call is not actually recursive.