Reputation: 79
I want to create X amount of random objects (100 in this example) in NodeJS. These objects have random values plus I want them created at randomIntervals. In order to accomplish this I wrote code similiar to this:
i=0;
while (i < 100){
randomNum1 = Math.floor(Math.random()*100);
randomNum2 = Math.floor(Math.random()*100);
randomIntervalTime = Math.floor(Math.random()*100);
timeOutInterval = setTimeout(function(){
return new SomeObject(randomNum1, randomNum2)}, randomIntervalTime);
i++;
}
The issue is that the value aren't preserved for the callback and it will just generate 100 new objects with all the same values (the last values created in the loop)
I realize this is because of some issue with the way callbacks work that I don't totally grasp, but my question is how would someone accomplish this in Nodejs.
Upvotes: 0
Views: 1831
Reputation: 64312
The original code places 100 callbacks into the event queue. Then, as each one executes, it uses the values stored in randomNum1
and randomNum2
. Note when the first callback starts running, the while loop has already completed and the values of randomNum1
and randomNum2
are no longer changing. This explains why your code uses the same values each time. The fix for this is easy - simply move the definitions for randomNum1
and randomNum2
inside the scope of the function creating the new objects like so:
var createNewObject = function() {
var randomNum1 = Math.floor(Math.random()*100);
var randomNum2 = Math.floor(Math.random()*100);
return new SomeObject(randomNum1, randomNum2);
};
var i = 0;
while (i < 100) {
var randomIntervalTime = Math.floor(Math.random()*100);
setTimeout(createNewObject, randomIntervalTime);
i++;
}
Upvotes: 1