Is it possible to run this \"indefinitely\", without causing stack overflow or running out of memory?
function eternal(){
var time = recalculateTime();
This is not actually a recursive call because the first invocation of eternal()
has actually finished before the setTimeout()
calls the next one. So, it's not technically recursion and does not build up the stack over time. It can run forever without any buildup and this is a perfectly fine way to keep something running over and over.
In response to one of your comments, javascript is not multi-threaded so it does not create multiple threads for timers. Each timer event that fires just puts an event into the event queue and if no JS is running at the time, that event is triggered (thus calling the callback function). If JS is running at the time, the JS engine waits until the currently executing JS finishes and then services the next event in the event queue (thus calling the callback).
That should be fine. Once setTimeout
runs it will return from the eternal
function before it's calls it again.