Possible Duplicate:
Javascript closure inside loops – simple practical example
How can I make this work?
// Phrases
var phrases = new Array();
phrases[0] = 'Phrase 1';
phrases[1] = 'Phrase 2';
phrases[2] = 'Phrase 3';
for (var i = 0; i < phrases.length; i++) {
var content = phrases[i];
$('#phrase').html(content).slideDown('slow').delay(1000).fadeOut('slow');
};
Here’s the HTML:
<p id="phrase"></p>
Passing the content variable into the html() function I noticed that content is always equal to the last phrase in the array, and the loop runs the slide / delay / fade functions 3 times.
I know that this is something to do with closures inside a for loop and I’ve looked at countless examples, but I just can’t get my head around it. Can someone solve and explain this one to me please?
EDIT: Apologies for being unclear before, I have edited this question to include the HTML and the array in question.
Functionality: Different phrases are held in the phrases[] array, I would like to insert the phrase into the <p> element, then slide that element down, leave it on screen for a second, then fade it out. Then I would like to move on to the next phrase in the phrases[] array and perform the same functions.
You don’t actually have an issue with closures, it is just setting the
innerHTMLtocontenton every iteration, which doesn’t take into account the effects which need to be completed first.jsFiddle.