Javascript force GC collection? / Forcefully free object?

后端 未结 3 492
不知归路
不知归路 2020-12-14 01:29

I have a js function for playing any given sound using the Audio interface (creating a new instance for every call).

This works quite well, until about the 32nd call

3条回答
  •  攒了一身酷
    2020-12-14 02:28

    I see at least one (or two) flaws:

    snd = new Audio(url);
    

    has no var in front of it, so snd is assigned to the global scope. That's usually not what you want: it clutters the global name space and if another script (e.g., an extension) incidentally uses snd, things will be a mess.

    And that's also why

    delete snd;
    

    doesn't work: you can't delete global variables:

    When declared variables and functions become properties of a Variable object — either Activation object (for Function code), or Global object (for Global code), these properties are created with DontDelete attribute.

    So, use

    var snd = new Audio(url);
    

    instead. BTW, you can't force the JavaScript engine to do garbage collection.

提交回复
热议问题