I have some questions concerning JavaScript loops.
Questions :
- Why does a JavaScript loop freeze the browser
- Why is the drawing slow even do it’s running at 1 draw every 1ms and it’s drawing the simplest thing!
- What’s the solution? flash is dying, what do we do now?
Here is the canvas code to try for yourself :
<!doctype html>
<html>
<head>
</head>
<body>
<canvas id="c" width="400" height="400"></canvas>
<script type="text/javascript">
var c = document.getElementById( 'c' );
ctx = c.getContext( '2d' );
var x = 100;
ctx.fillStyle= '#f00';
function loop()
{
ctx.fillRect( x, 100, 20, 20 );
++x;
}
setInterval( loop, 1 );
</script>
</body>
</html>
JavaScript is single threaded. The state of the DOM cannot change whilst javascript code is running or race conditions would occur. This means no drawing / reflow.
It’s not running at 1ms, it’s running at 10ms because browsers do not allow you to loop that tightly.
Use requestAnimationFrame and run your game at 60 FPS, why do you need more?
Example using (webkit) requestAnimationFrame which runs smoothly for me.