I am trying to understand why memory continues to accumulate in Chrome (version 38.0.2125.111) when drawing images to a HTML5 Canvas. Using the below code, I watch the 'Memory' figure for my tab in Chrome's Task Manager increase by about 300-400kb per second up to anywhere between 35mb and 50mb before dropping right down to about 5mb. After that happens once, as the process continues the memory just keeps climbing and climbing (i.e. it nevers appears to be cleared again). If I click 'Go' again or even if I refresh the page the memory does not drop at all.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function tryit () {
var px=1;
var py=1;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var canvas2 = document.getElementById('myCanvas2');
var context2 = canvas2.getContext('2d');
var img=document.getElementById("img1");
var thereps=document.getElementById("txtreps").value;
context2.drawImage(img,0,0);
var counter=1;
function loop() {
counter=counter+1;
px=Math.random()*1000;
py=Math.random()*800;
context.drawImage(canvas2, 0, 0, 10, 16, px,py,10,16);
if (counter>=thereps) {
clearInterval(myTimer);
context.clearRect(0,0,1034,814);
alert("done");
}
}
myTimer = setInterval(loop,17);
}
</script>
</head>
<body>
Loop:
<input id="txtreps" type="text" size="6" value="10000"/>
times
<input type="button" onclick="tryit();" value="Go"/>
<div style="position:relative;width:1034px;height:814px;border:1px solid grey;">
<canvas id="myCanvas" width="1034" height="814" style="visibility: visible; position: absolute; top:0; left: 0;border:1px solid black;" ></canvas>
<canvas id="myCanvas2" width="10" height="16" style="visibility: hidden;position:absolute; left:0px; top:0px;border:1px solid red;" ></canvas>
<img id="img1" src="untitled.png" width="10" height="16" style="visibility: hidden; position: absolute; top:0; left: 0;border:1px solid green;">
</div>
</body>
</html>
This is a micro example of how my larger application runs. The user input triggers the animation to start and they generally run for a maximum of 5 seconds and then stop. The user then gives input again to start another animation. This can be repeated hundreds of times. As mine has more images I am finding the memory increasing at a rate of 3-4mb per second and before long I am hitting the Aw Snap error as the memory has gotten over 1.4gb. Am I doing something wrong? Is there any way I can force the 'clean up' process that the browser seems to apply just once more often?
Note that when I set my loop up using requestAnimationFrame instead of a timer, I find that the memory increase occurs even if I do not actually draw anything (i.e. I make no drawImage call).