user1043696
user1043696

Reputation: 23

Javascript Game Loop

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>

Upvotes: 2

Views: 4713

Answers (3)

Joszs
Joszs

Reputation: 41

The reason of the framerate drop and eventually the browser freeze occurs because of the memory occupied by the canvas element. I already answered this question. You can find the thread here.

Each time you draw something to the canvas that operation is saved to the path of the canvas. This path occupies more memory each time you draw something on the canvas. If you don't empty the path of the canvas you will have framerate drops. For example look at the execution time difference between your javascript and the javascript below which clears the canvas path,

var c = document.getElementById( 'c' );
ctx = c.getContext( '2d' );
var x = 100;
ctx.fillStyle= '#f00';

function loop()
{
    ctx.beginPath(); 
    ctx.fillRect( x, 100, 20, 20 );

    ++x;
}
setInterval( loop, 1 );

Upvotes: 0

Raynos
Raynos

Reputation: 169391

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.

Upvotes: 10

SLaks
SLaks

Reputation: 887453

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.

Upvotes: 2

Related Questions