javascript - Simultaneous setIntervals - only first one running -
i'm designing web page has moving clouds in background. code uses jquery , looks this.
browserwidth = 0; browserheight = 0; clouds = 4; cloudspeed = 50; $(function() { browserwidth = $(window).width(); browserheight = $(window).height(); for(i = 0; < clouds; i++) { createcloud(cloudspeed); } }); function movecloud(cloud) { offset = cloud.offset(); posx = offset.left; posx--; if(posx < -250) { posx = browserwidth; } cloud.offset({ left: posx }); } function createcloud(speed) { posy = math.floor(math.random() * (browserheight / 2.5)); posx = math.floor(math.random() * (browserwidth - 255)); cloud = $("<div></div>").addclass("cloud").appendto("body").offset({ top: posy, left: posx }); setinterval(function() { movecloud(cloud); }, speed); }
basically uses createcloud
function create fours clouds (divs background image) initializes div , sets interval using setinterval
. in interval function call function movecloud
moves div 1 pixel left. see code above.
my problem moves 1 of divs. i've read should okay use multiple intervals simultaneously.
what's wrong code?
the problem have one, global, cloud
.
add var
in front of declaration :
var cloud = $("<div></div>").addclass("cloud").appendto("body").offset({
when don't use var keyword, make variable global.
Comments
Post a Comment