I was wondering what is the best way to implement a renderer in JavaScript. It's not the content part of the rendering that's really important here - I would rather like to hear when and how to effectively run the renderer code.
Currently, I have wind开发者_Python百科ow.setInterval(renderFunc, 1000 / 20)
, which will just render a frame each 50 ms (i.e., fps = 20).
The point is that faster computers won't render more frames, moreover slower computers will not be able to catch up with 20 fps, so the function is called more than the computer might be able to handle.
I was thinking of a while(true)
loop, but this uses 100% CPU and will freeze the computer itself - so actually my game (the renderer is of my 3D game) won't be playable anymore at all since you cannot click on buttons anymore.
What is the most efficient option in this scenario, or is there a better method that has not come to my mind?
Thanks in advance.
There's a feature that is made specifically for animation, called window.requestAnimationFrame
. This means that the browsers chooses when to call your animation function instead of you hardcoding intervals. Lots of benefits from using it:
- Faster computers will get higher frame rates
- Windows/tabs that aren't visible are updated much less often
- Varying frame rate depending on CPU usage
This article explains how to use it in a cross browser fashion: http://paulirish.com/2011/requestanimationframe-for-smart-animating/
The article also links to http://jsfiddle.net/paul/XQpzU/2/
You could time how long a frame render takes, and adjust frame spacing to achieve an acceptable load. E.g., if your current frame took 5ms to render, and you want 50% load, wait 5ms before the next frame. You'll want to put some sanity checks on it, and also probably use times from the last several frames.
Look into trying the while(true)
loop inside of a web worker thread. This should prevent the browser from locking up. Note that you can't directly manipulate a <canvas>
or any other part of the DOM from within the worker thread.
https://developer.mozilla.org/En/Using_web_workers
"setInterval() will pass the number of milliseconds late the callback was called" -- https://developer.mozilla.org/en/window.setInterval
You could use this to dynamically adjust your interval time.
N.B. MDC docs are for Javascript as implemented by Mozilla, not ECMA Script or other implementations. You should check if this works in other browsers.
精彩评论