Can I trigger JavaScript's garbage collection?

后端 未结 9 2030
不知归路
不知归路 2021-01-31 07:17

I want to trigger JavaScript garbage collection. Is it possible? Why would I want to, or not want to, do this?

相关标签:
9条回答
  • 2021-01-31 07:53

    You can trigger manually JavaScript garbage collector in IE and Opera, but it's not recommended, so better don't use it at all. I give commands more just for information purpose.

    Internet Explorer:

    window.CollectGarbage()
    

    Opera 7+:

    window.opera.collect()
    
    0 讨论(0)
  • 2021-01-31 07:53

    If it is true that there is no way to trigger a GC, as implied by the other answers, then the solution would be for the appropriate browser standards group to add a new JavaScript function to window or document to do this. It is useful to allow the web page to trigger a GC at a time of its own choosing, so that animations and other high-priority operations (sound output?) will not be interrupted by a GC.

    This might be another case of "we've always done it this way; don't rock the boat" syndrome.

    ADDED:

    MDN documents a function "Components.utils.schedulePreciseGC" that lets a page schedule a GC sometime in the future with a callback function that is called when the GC is complete. This may not exist in browsers other than Firefox; the documentation is unclear. This function might be usable prior to animations; it needs to be tested.

    0 讨论(0)
  • 2021-01-31 07:55

    I was reading Trevor Prime's answer and it gave me a chuckle but then I realized he was on to something.

    1. Reloading the page does 'garbage-collect'.
    2. location.reload() or alternatives to refresh page.
    3. JSON.parse/stringify and localStorage.getItem/setItem for persistence of needed data.
    4. iframes as reloading pages for user experience.

    All you need to do is run your code in an iframe and refresh the iframe page while saving useful information into localStorage. You'll have to make sure the iframe is on the same domain as main page to access its DOM.

    You could do it without an iframe but user experience will no doubt suffer as the page will be visibly resetting.

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