Friday 15 December 2017

javascript - How can I create multiple setInterval()s dynamically?





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)

);
}

class="post-text" itemprop="text">
class="normal">Answer



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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...