Simultaneous setIntervals - only first one running

javascript, jquery, loops, setinterval

Solution

The problem is that you have only one, global, `cloud`.

Add `var` in front of the declaration :

var cloud = $("<div></div>").addClass("cloud").appendTo("body").offset({

When you don't use the var keyword, you make the variable global.

Problem

I'm designing a web page that has moving clouds in the background. My code uses jQuery and looks like this. ``` browserWidth = 0; browserHeight = 0; clouds = 4; cloudSpeed = 50; $(function() { browserWidth = $(window).width(); browserHeight = $(window).height(); for(i = 0; i < 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 it uses `createCloud` function to create fours clouds (divs with background image) which initializes the div and sets an interval using `setInterval`. In the interval function I call function `moveCloud` that moves the div one pixel left. See the code above. My problem is that it moves only one of the divs. I've read that it should be okay to use multiple intervals simultaneously. What's wrong with the code?

Original source