javascript - Adding a counter ID to a setInterval loop -
i'm working 3 functions:
startbubblemachine()
starts process of making bubblesmakebubble()
makes bubblebubbleid
identify it. appends div.killbubble()
removes bubble
the timings creation of bubbles randomised using function randomint
generates random int within range.
i'm struggling incrementing of bubbleid
, needed create new bubble , ensure correct bubble destroyed. cannot work out @ stage increment.
function startbubblemachine(){ console.log('starting bubble machine'); var bubbleid = 1; setinterval(makebubble(bubbleid), randomint(6000, 1000)); }
this function pretty simple. initialises bubbleid
and sets interval between 1s , 6s call makebubble()
, passing bubbleid
this stuck
function makebubble(bubbleid){ console.log('making bubble number '+bubbleid); $('.wrapper').append('<div class="db-bubble db-bubble-'+bubbleid+'></div>'); killbubble(bubbleid); // kill bubble current id bubbleid++; // increment current id }
the bubble made, killbubble()
function called immediately. passes bubbleid
ensure correct bubble murdered.
and increments bubbleid
ready next bubble creation. but bit wrong, i'm sure.
finally, killbubble()
has received bubbleid
must murder. waits 2s, removes.
function killbubble(bubbleid){ settimeout(function(){ // murder time $(".db-bubble-"+bubbleid).remove(); }, 2000); // kills bubble }
my issue the process runs once. bubble 1 created, bubble 1 removed. bubble 2 never gets created.
jsfiddle
as using setinterval
, bubbleid
being passed value (only objects passed reference) makebubble
funnction. use different name global counter parameter name in makebubble
function.
Comments
Post a Comment