Reputation: 28188
Not sure where I have gone wrong.
I have the following code which creates a "bubble" on the page every 1-2 seconds, and then destroys each bubble after 6 seconds.
The code generally works fine except for the variable bubbleID
which shows as undefined
despite being initialised.
function startBubbleMachine(){
var bubbleID = 1;
setInterval(function makeBubble(bubbleID){
var wh = randomInt(143, 50);
console.log('making bubble number '+bubbleID); // this shows undefined
$('.wrapper').append('<div class="db-bubble db-bubble-'+bubbleID+'" style="transform:rotate('+randomInt(20, 1)+'deg);left:'+randomInt(100, 1)+'%;width:'+wh+'px;height:'+wh+'px;"></div>');
killBubble(bubbleID);
bubbleID++; // this doesn't seem to get used
}, randomInt(2000, 1000));
}
I'm initialising the bubbleID
to 1:
var bubbleID = 1;
I'm then passing the bubbleID
in the function within the setInterval
setInterval(function makeBubble(bubbleID){
...
});
And then I'm incrementing it within that function:
bubbleID++;
Where am I going wrong?
Upvotes: 0
Views: 65
Reputation: 414076
You're hiding the var bubbleID
variable by including a like-named parameter in the anonymous function. Get rid of the formal parameter.
setInterval(function makeBubble( ){
// ^
Including that parameter name does not pass the variable; it simply says that the function expects a parameter to be passed. There's no need for that, however, because the code in that timer function can "see" the bubbleID
variable through closure.
Upvotes: 8