How to remove javascript canvas

I want to have a bunch of objects, say:

function Block() {
  this.canvas;
}

blocks = [];

And in some cases I will indicate:

block[x] = new Block();

and then:

block.canvas = document.createElement('canvas');

But I also want to delete this new canvas in order to free up memory sometimes. I just need to do:

block.canvas = null; (or whatever the appropriate method is)

And then javascript will free the memory at some point? Or is there an explicit way to delete an object and free up memory?

Thank!

+5
source share
4 answers

The memory that is taken by objects referenced anywhere is recovered in JavaScript by garbage collection ( MDN document on this ).

So, to free up memory, you just need to delete all references to objects canvas, and the next time you run the garbage collector, the memory will be freed again.

, , block.canvas = null; ( /) delete block.canvas.

, . DOM !

+7

, . DOM, , , . appendChild, removeChild


, , , . .

+3

Javascript delete:

delete block.canvas;

: http://www.openjs.com/articles/delete.php

+1

javascript mark-and-swap GC, ( ) .

, <canvas> , :

  • , block.canvas = null, .
  • <canvas> DOM, canvas.parentNode.removeChild(canvas),

DOM, , <canvas> DOM, , .

PS: I noticed several answers to define a keyword deleteto remove a property canvas, but it really is not necessary, GC works as expected, immediately after block.canvasthe value is set null, since a deletecan lead to a slower start of V8 , my advice is to prevent use delete.

0
source

All Articles