Jump to content

Problems with array not existing in setInterval


shadowayex

Recommended Posts

I have an array of DOM items and I have this line inside of a for loop:

setInterval(function() { items[i].style.top = items[i].offsetTop + 1 + "px"; }, interval);

I get an error telling me items does not exist. I'm thinking it's a scoping problem or something of the sort. I was wondering how to go about getting at these DOM items in the anonymous function inside the setInterval function.

Link to comment
Share on other sites

By the time that function runs, the loop is finished and i is set to one more than the length of the array, so that's why items doesn't exist. items[i - 1] is the last element in the array at that point. A closure is one way to handle that:

function (el){  setInterval(function() { el.style.top = el.offsetTop + 1 + "px"; }, interval);}(items[i]);

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...