Recursive setTimeout in javascript

前端 未结 2 737
长情又很酷
长情又很酷 2021-01-20 11:11

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

function eternal(){
    var time = recalculateTime();
          


        
2条回答
  •  抹茶落季
    2021-01-20 11:29

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

提交回复
热议问题