I have some questions concerning JavaScript loops.
Questions :
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>
Why does a JavaScript loop freeze the browser ( does not happen in C++ )
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.
Why is the drawing slow even do it's running at 1 draw every 1ms and it's drawing the simplest thing!
It's not running at 1ms, it's running at 10ms because browsers do not allow you to loop that tightly.
What's the solution? flash is dying, what do we do now?
Use requestAnimationFrame and run your game at 60 FPS, why do you need more?
Example using (webkit) requestAnimationFrame which runs smoothly for me.
One millisecond is an extremely short interval.
It's such a short interval that your code will be running in the UI thread almost continually, leaving the browser unresponsive.
You need to leave pauses to give the user time to interact with the page.
Use an interval of at least ten, and preferably one hundred, milliseconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With