Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Game Loop

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>
like image 277
user1043696 Avatar asked Mar 20 '26 14:03

user1043696


2 Answers

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.

like image 115
Raynos Avatar answered Mar 23 '26 03:03

Raynos


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.

like image 38
SLaks Avatar answered Mar 23 '26 04:03

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!