I have a script that needs a function to be run multiple times per
object, but the number of objects is set in a variable by the
user.
It would work like
this
dothis(1);
dothis(2);
dothis(3);
However
this doesn't work
for (var i = 0;
i < howMany; i++)
{
setInterval(
function()
{
dothis(i);
},
(Math.floor(Math.random() * 10) + 1)
);
}
You need
to snapshot the value of i in a local scope otherwise it gets
dynamically 'regenerated' at execution time, which means the value would then always be
howMany, since the CPU lock, created by the main function,
prevents your setInterval/setTimeout
functions to execute before the loop is
ended.
for (var i = 0;
i < howMany; i++)
{
setInterval(
function(j)
{
return function() { dothis(j); };
}(i),
(Math.floor(Math.random() * 10) + 1)
);
}
See
How do JavaScript closures
work? for further reference.
No comments:
Post a Comment