Recursive setTimeout in javascript

前端 未结 2 736
长情又很酷
长情又很酷 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).

    0 讨论(0)
  • 2021-01-20 11:37

    That should be fine. Once setTimeout runs it will return from the eternal function before it's calls it again.

    0 讨论(0)
提交回复
热议问题