Variable inside SetTimeout undefined (out of scope?)

时间:2017-08-05 11:08:55

标签: javascript variables scope settimeout

I am not able to find a solution on SO about the following problem:

Simply put: I want a few divs "falling" down from random spots. When they reach the end of the div (banner) they will stop their transition, go back to the top, and start falling again.

The problem: after they are back at the top, flock[i] becomes undefined inside the setTimeout.

var rngHorMin = 0;
var newTop = 0;
var rngHorMax = document.body.clientWidth;
var banner = document.getElementById("flock-banner");
var flock = document.getElementsByClassName("flock");
var disTop = new Array();

for(var i=0;i<flock.length;i++){
var rngHor = Math.floor((Math.random() * rngHorMax) + rngHorMin);
var rngRot = Math.floor((Math.random() * 360) + 0);
flock[i].style.right = rngHor + "px";
flock[i].style.webkitTransform = "rotate(" + rngRot + "deg)";
}
setInterval(function party(){
for(var i=0;i<flock.length;i++){

if(disTop[i] < 0){
    setInterval(function(){
        console.log(flock[i]); // <--- undefined??
    },2000);
}
if(!disTop[i]){
disTop[i] = newTop;
newTop = newTop + 20;
}else{
disTop[i] = disTop[i] + 20; 
}
flock[i].style.top = disTop[i] + "px";
if(disTop[i] > (banner.offsetHeight + 100)){
    flock[i].style.webkitTransition = "none";
}
if(flock[i].style.webkitTransition == "none"){
    disTop[i] = -100;
}
}
},1000);

All help appreciated :)

0 个答案:

没有答案