2

I've decided to play around with HTML5's canvas, and of course that means I'm going to try writing a pong game. At the moment, I am trying to figure out how to cap my framerate. This is fairly easy in other languages, but finding a way to delay execution in Javascript seems to be a bit tougher.

Here is what I have so far:

while(true) {
    var begin = (new Date()).getTime();

    //Draw stuff to the canvas

    var end = (new Date()).getTime();
    if ((end-begin) < 33.333 ) {
        //delay (1000/(30-(end-begin)))
    }
}

Obviously, frame rates will be wildly different due to how each javascript engine performs, but I want to cap the maximum framerate at 30FPS. I don't really see how setTimeout() would accomplish this task. What would be the best way to do this?

3
  • 1
    Have you tried setInterval? There are certainly some issues to be aware of, like a non-linear clock but at least this allows you to 'sleep' a bit. Commented Dec 21, 2012 at 17:55
  • 4
    Check out requestAnimationFrame (click me), it will give you about a 60ish FPS (or whatever best fits the client). Commented Dec 21, 2012 at 17:56
  • Related to the above comment: programmers.stackexchange.com/questions/175934/whats-the-best-way-to-use-requestanimationframe-and-fixed-frame-rates Commented Dec 21, 2012 at 18:00

1 Answer 1

7

There is no delay / wait in JavaScript. You can use functions like window.setTimeout to call a function after certain time has elapsed, example:

window.setTimeout(function() {
    // do something interesting
}, 2000 /* but after 2000 ms */);

Or say you want to paint a frame every 33 ms (~30 fps), you will code it like:

window.setInterval(function() {
    // paint my frame 
}, 33);
Sign up to request clarification or add additional context in comments.

1 Comment

I think it is window.setInterval rather than window.setTimeInterval.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.