Adventure Land - The Code MMORPG

Adventure Land - The Code MMORPG

View Stats:
beginners question about setInterval
can someonne explain this?

Code1
---------
setInterval(function(){
if (!counter){
var counter = 0;
game_log([counter]);
}
else{
counter++;
game_log([counter]);
}
},1000/4);

interval works but keeps setting to 0 becouse restart and counter isn't saved outside function -> 0 is spammed */


code2
--------
function Count(counter){
if(!counter){
counter = 0;
game_log([counter]);
}
else{
counter++;
game_log([counter]);
}
}

setInterval(Count(), 1000/4);

/* i expect the same spam of zeros (i know the code can't count like intended), but only 1 zero apears in the log and then the code stops
Last edited by Korosevar; Aug 1 @ 7:49am
< >
Showing 1-3 of 3 comments
jerrak Aug 1 @ 2:51pm 
First example, you're initializing var counter inside the loop/setIntervalfunction so every time it will set it to zero. Try:
var counter = 0; setInterval(function(){ counter++; game_log([counter]); },1000/4);
ty, i phrased my question kinda bad :). the problem is more wy the interval doesn't work at the second code. i know everytime i loop the Count() function, it wil restart var counter = 0. What i realy don't understand is wy at the second code, the interval doesn't repeat itselve. Is it becouse of the game logic, that only allows one interval that looks like setInterval(function(){ code}, 1000/4); and im not allowed to replace function() with a named self created function. or am i making a javascript reasoning mistake at the second code -> i would expect it to loop/repeat the function Count(), and spam 0's in the game_log
Last edited by Korosevar; Aug 2 @ 6:07am
FYI
found the answer in discord channel.

it was a syntax problem where
setInterval(Count(), 1000/4);
should be
setInterval(Count, 1000/4);
< >
Showing 1-3 of 3 comments
Per page: 15 30 50