/    Sign up×
Community /Pin to ProfileBookmark

array not available in setTimeout

I’m trying to create an image rotator, but whenever I try to access an array element within the loop (only within setTimeout()), I’m just getting a value of ‘undefined’.

[code=php]images = new Array(“test1”, “test2”, “test3”);
for (var i = 0; i < images.length; i++) {
setTimeout(function() { alert(images[i]); }, i*500);
}[/code]

If I had to guess, I would say that images[] is no longer in scope when the function is actually executed. Is this the case? Thanks!

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@toicontienJan 04.2008 — If the images array is a global variable, then it should be available. If the images array is not a global variable, and instead is created inside another function or object, then no. The images array is not available. The callback function for the setTimeout function is executed in the window object's scope.
Copy linkTweet thisAlerts:
@jon23dauthorJan 04.2008 — Okay, so, if you plug the code I wrote into <script> tags, it doesn't work! How do I make the images variable available to the inline function within setTimeout?
Copy linkTweet thisAlerts:
@toicontienJan 04.2008 — Oh! It's the variable "i" that isn't available. This code should work:
var Images = {
i: 0,
urls: ["test1", "test2", "test3"],

GetTimeoutFn: function(i) {
return function() {
alert(Images.urls[i]);
};
}
};

for (Images.i; Images.i &lt; Images.urls.length; Images.i++) {
setTimeout(Images.GetTimeoutFn(Images.i), Images.i * 500);
}
Copy linkTweet thisAlerts:
@jon23dauthorJan 04.2008 — Excellent, that worked perfectly! It never occurred to me that i could have been the issue. Thank you very much.
Copy linkTweet thisAlerts:
@mrhooJan 04.2008 — [CODE] window.images= ["test1", "test2", "test3"];
window.timer_1= setInterval(function() {
var i= window.images.length;
if(i) alert(window.images.shift());
else clearInterval(window.timer_1);
}, 500);[/CODE]
×

Success!

Help @jon23d spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...