Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneous setIntervals - only first one running

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?

like image 504
MikkoP Avatar asked Dec 16 '22 12:12

MikkoP


2 Answers

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.

like image 199
Denys Séguret Avatar answered Dec 30 '22 13:12

Denys Séguret


You haven't declared cloud as a local variable, but in the global context. For more information, see this: http://www.webdevelopersnotes.com/tutorials/javascript/global_local_variables_scope_javascript.php3

like image 42
mrks Avatar answered Dec 30 '22 13:12

mrks