Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive setTimeout in javascript

Is it possible to run this "indefinitely", without causing stack overflow or running out of memory?

function eternal(){
    var time = recalculateTime();
    doSomething();
    setTimeout(eternal,time);
}

setTimeout(eternal,200000);

I'm not using setInterval, because the triggering time is variable.

like image 458
Guillermo Gutiérrez Avatar asked Aug 16 '26 03:08

Guillermo Gutiérrez


1 Answers

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).

like image 70
jfriend00 Avatar answered Aug 20 '26 01:08

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!