scope - Javascript game loop state in an anonymous function -


i'm messing around canvas, , starting reading bunch of game loop snippets/posts , combining them best 1 possible.

i came upon snippet today (it's part way through a post, make further iterations on later. i'm integrating ideas go), it's perplexing me little.

game.run = (     function() {         var loops = 0;         var skipticks = 1000 / game.fps;         var maxframeskip = 10;         var nextgametick = (new date).gettime();          return function {             loops = 0;              while ((new date).gettime() > nextgametick && loops < maxframeskip) {                 game.update();                 nextgametick += skipticks;                 loops++;             }              game.draw();         };     } )();  game._intervalid = setinterval(game.run, 1000 / game.fps); 

so game.run gets assigned result of outer function, inside function. inside function relies on nextgametick, defined in outer function...

so game keeping state in outer anonymous function? if so, ideas why did that?

and e.g. loops, set 0 every call, declared outside avoid re-declaring variable again each time?

yes will.

the local frame of function returned inside local frame of game.run function. therefore, variable gets changed in game.run around function return persistent. parent frame of function inside of game.run time try reference nexttick variable.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -