Is there memory leak issue if not calling clearTimout after calling setTimeout

后端 未结 2 763
栀梦
栀梦 2020-12-16 19:32

After calling setTimeout, is there memory leak issue without calling clearTimeout?

Thanks.

相关标签:
2条回答
  • No. clearTimeout only needs to be called if you want to stop a pending setTimeout from happening. After the setTimeout happens, the timer id is no longer valid but fortunately calling clearTimeout with an invalid timer id is harmless.

    If you see memory leaks happening the problem is somewhere else.

    0 讨论(0)
  • 2020-12-16 20:02

    There are times when setTimeout can cause memory leaks... see the following article: setTimeout memory leaks

    Be warned that IEx has a garbage-collector subtlety, though; I think that if you reference a DOM variable in a Javascript closure, then the collection mechanism gets confused and it doesn't get trashed at the end of the request: eventually this becomes a memory leak. I think it's because DOM variables and internal JS variables get collected by two different collectors, and they don't communicate properly about what's no longer being used.

    I think you can fix this by setting the variable to null:

    setTimeout(function(){
        myFunction(parameter); 
        parameter = null
    }, myTimeout);
    

    This explicitly sets the garbage collection in motion.

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