r/shittyprogramming • • Apr 12 '16

Easy JavaScript game loop

Post image
277 Upvotes

37 comments sorted by

View all comments

33

u/fukitol- Apr 12 '16

all it's missing is var isRunning = true; in the global scope, if(!isRunning) { return; } window.on('stopRunning', function() { isRunning = false; }); in bar() and processEvents(); in foo()

It's practically a game!

2

u/[deleted] Apr 12 '16

Being serious: is it bad practice to have state variables in the global scope like that, in general?

3

u/fukitol- Apr 12 '16

Generally, with something like a game loop, there's going to be some sort of state being stored at the global scope. For instance, I might store the player there. But most things should rely solely on events, and anything in the global scope should be kept to a minimum.

4

u/the_omega99 Apr 12 '16

Eh? It doesn't have to be global. Assuming that only the loop needs to be aware that it's running, you can encapsulate it in something where it isn't accessible.