0 Replies - 333 Views - Last Post: 25 January 2013 - 02:49 AM

#1 sam_benne  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 16
  • View blog
  • Posts: 732
  • Joined: 16-January 08

Dynamic SVG Memory Leak

Posted 25 January 2013 - 02:49 AM

I have a simple script that will create 500 randomly generated circles. This is in a loop so they will keep getting removed and re-added. However this is causing a leak.

I also replicated the code with Raphael.js and that did not leak. Just can't see what is causing the issue.

<div id="svgdiv" style="width:600px; height:500px;"></div>
<input type="button" value="start" onclick="start()">
<input type="button" value="stop" onclick="stop()">
<input type="button" value="stopClean" onclick="stopClean()">
<script type="text/javascript">
	var svg,
		interval;

	window.onload = function(){
		createSVG();
	}

	function createSVG(){

		var div = document.getElementById("svgdiv");
		while(div.hasChildNodes() ){
			div.removeChild(div.lastChild);
		}

		svg = createSvgElement("svg");
		svg.style.position = "absolute";
		svg.style.width = "600px";
		svg.style.height = "500px";
		svg.setAttributeNS(null, "version", "1.2");
		svg.setAttributeNS(null, "baseProfile", "tiny");
		div.appendChild(svg);
		div = null;
		createElements();
	}

	function createElements(){

		removeElements();
		var temp = document.createDocumentFragment(),
			element = createSvgElement('svg:circle'),
			i, transform;

		for(i = 0; i < 500; i++){
			element = element.cloneNode(false);
			element.setAttributeNS(null, "r", Math.random() * 10);
			transform = "translate(" + Math.round(Math.random() * 600) + "," + Math.round(Math.random() * 500) + ")";
			element.setAttributeNS(null, "transform", transform);
			element.setAttributeNS(null, "fill", "#CC0000");
			temp.appendChild(element);
		}
		svg.appendChild(temp);
		temp = element = i = transform = null;
		interval = setTimeout(function() {
			createElements();
		}, 100);
	}

	function removeElements() {
		while(svg.firstChild ){
			svg.removeChild(svg.firstChild);
		}
	}

	function createSvgElement (name) {
		return document.createElementNS("http://www.w3.org/2000/svg", name);
	}

	function start(){
		interval = setTimeout(function() {
			createElements();
		}, 1000);
	}

	function stop(){
		clearTimeout(interval);
	}

	function stopClean() {
		clearTimeout(interval);
		var svg = document.getElementById("svgdiv").childNodes[0];
		while(svg.firstChild ){
			svg.removeChild(svg.firstChild);
		}
		svg = null;
	}
</script>



Is This A Good Question/Topic? 0
  • +

Page 1 of 1