Reputation: 1109
I'm trying to make a video game engine which must run the render
function as a loop. When this function is finished, I want to run it again, and again, and again... But when I try this :
function render() {
// some code here which takes ~ 0.00015 second to run
}
while(1) { render(); }
The browser freeze in a few seconds. So I've tried another way :
function render() {
// some code here which takes ~ 0.00015 second to run
}
setTimeout(render);
// I've tried also
setTimeout(render, 1);
Also :
function render() {
// some code here which takes ~ 0.00015 second to run
setTimeout(render);
// OR
setTimeout(render, 1);
}
But that runs the function only ~ 500 times at a second, I want to run it ~ 5000 times. That's possible if I look the running time (0.00015 second) but I can't find a way to do that.
Does anyone have an idea ?
Upvotes: 0
Views: 620
Reputation: 5835
What you want to do is use window.requestAnimationFrame
this way:
function render() {
window.requestAnimationFrame(render);
}
window.requestAnimationFrame(render);
You can never get an "infinite" amount of calls, that will depend on how strong your hardware is. You can also easily calculate "delta time" (amount of time passed between two consecutive render
calls) to make the game animation smooth for any user no matter what their hardware is.
Upvotes: 3