You should never use a while (true)
loop (or anything that will always result in true
).
while (true) {
console.log("Most likely will crash the browser!");
}
I didn't make it a code snippet because it will most likely crash your browser.
What it will do (in this case) is output the string
an infinite number of times (until the browser crashes).
Most likely will crash the browser!
Most likely will crash the browser!
Most likely will crash the browser!
...Stops responding...
A good alternative for a game loop is to use requestAnimationFrame()
.
The great things about it are:
- It's supported in all browsers (even Internet Explorer^)!
- It doesn't crash your browser.
- It only runs when the tab is focused. This means it won't take up resources in the background.
According to MDN Web Docs, it states that:
The window.requestAnimationFrame()
method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint.
It returns an long
integer value, which can be used to call window.cancelAnimationFrame()
to cancel it.
A simple example is below.
function loop() {
// You don't need 'window', because by default it's global.
requestAnimationFrame(loop);
// Example...
GameClass.updateGame();
}
The reason you pass the loop()
function in requestAnimationFrame()
is because it will call that function to update on the next repaint, which is why the example GameClass.updateGame()
function is being called as a placeholder.
For more examples, please see the examples on MDN Web Docs. They are more advanced and will take too long to explain in this answer.
In summary, you should use the requestAnimationFrame()
function in place of the while (true)
loop to avoid the browser not responding.
^ Only supported in IE 10 and 11.