Function PS.Tick() is called every 100 milliseconds and its job is to call AI function of NPCs so they can move:
PS.Tick = function ()
{
"use strict";
for (NPCid = 0; NPCid < NPCnumber; NPCid++)
{
NPCAI(NPCid);
};
};
But I want the NPCs to not move simultaneously every 100 millisecond, but do it at their own frequency, so I tried this code:
PS.Tick = function ()
{
"use strict";
for (NPCid = 0; NPCid < NPCnumber; NPCid++)
{
var timeout = 0;
timeout = PS.Random (1000);
setTimeout("NPCAI(NPCid)",timeout);
};
};
Now, they don’t move at all. Why? How do I make them move at different time intervals?
A couple of possible reasons:
If
NPCidisn’t declared anywhere: Your code is throwing aReferenceError.If
NPCidis declared somewhere but it’s not a global: When you pass a string intosetTimeout, it doesn’t get evaluated in the current execution context and doesn’t have access toNPCid. In general, don’t pass strings intosetTimeout.If
NPCidis a global: When the delayed code is executed, they’ll all see the same value forNPCid, which is its value at the end of the loop.Instead: If you’re doing this on NodeJS (I’m just inferring this from what you’re doing), you can do this):
That works because on NodeJS (and Firefox),
setTimeoutcan accept arguments to pass to the function to call.If you’re not using NodeJS or Firefox, but you do have access to ES5’s
Function#bind, you can do this:Function#bindreturns a function that, when called, will call the original function with a specificthisvalue and the arguments you give it.If not, you can write your own
bind, or do it like this:That works by creating a function that, when called, turns around and calls NPCAI with the value we pass into it.