Will a recursive 'setTimeout' function call eventually kill the JS Engine?

前端 未结 1 1629
情书的邮戳
情书的邮戳 2020-12-01 18:27

Let\'s say I have some data that I need to get from the server about every 10 seconds. I would have a function that gets the data via AJAX and then call setTimeout to call

相关标签:
1条回答
  • 2020-12-01 18:59

    There's no actual recursion because the call to GetData is delayed and the JavaScript context is destroyed in the meantime. So it won't crash the JS engine.

    For your code sample, this is basically what will happen at the JS engine level:

    1. Initialize JS engine
    2. Create GetData function context
    3. Execute GetData statements including "setTimeOut"
    4. "setTimeOut" instruct the JS engine to call a function in 10 seconds
    5. Destroy GetData function context
    6. At this point, in terms of memory use, we are back to step 1. The only difference is that the JS engine stored a reference to a function and when to call it (lets call this data "futureCall").
    7. After 10 seconds, repeat from step 2. "futureCall" is destroyed.
    0 讨论(0)
提交回复
热议问题