Jump to content

Problems with array not existing in setInterval


shadowayex
 Share

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...