Leaving recursive functions running forever?

后端 未结 2 531
萌比男神i
萌比男神i 2021-01-25 10:36

I came across a function where it had a setTimeout inside with a timeout growing exponentially (timeout *= 2).

let timeout = 10000
fun         


        
相关标签:
2条回答
  • 2021-01-25 10:47

    This is not a recursive function call. The call to setTimeout will cause foo to be called by the JavaScript event loop at a later time.

    This code will not cause a stack overflow or any such problems. It should be completely safe.

    To understand how this works in-depth, I suggest reading up on the JS event loop and microtasks.

    0 讨论(0)
  • 2021-01-25 10:59

    Is this something that could lead to memory leaks?

    -If the function FOO() runs to completion before the timeout calls it again then no. The stack should be cleared.

    Is it better/clearer to still limit the number of calls to the function?

    -Yes, since your timeout variable will eventually overflow and may cause unintended results.

    Would other languages use such approach or are there different mindsets outside of JS world?

    -Depends on how the timer functions works for the library/language you use. But this seems like a simple way and valid way to have an increasing timeout.

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