Similar Question:
Understanding JavaScript closures
After going through the FAQ and multiple examples, I am still struggling to figure out why my code is not working as intended. Any hints or tips on what I might be doing wrong would be greatly appreciated. My goal is simple - display images one at a time on button click, spelling out a word using each letter (with fading in/out effects). Despite logging the correct values to the console, only the last image is being displayed. It seems like a typical "for loop showing only the last item" issue, but I can't seem to resolve it. Your guidance in understanding and fixing this problem is highly valued. Here's the snippet of the code without the HTML part (which consists of just a div that gets updated and a button):
$(document).ready(function () {
var word = 'abc';
$('#newWordButton').click(function () {
function animateLetters() {
function changeLetter() {
for (i = 0; i < word.length; i++) {
var currentLetter = word.charAt(i);
console.log(currentLetter);
$('#wordsDiv').fadeOut(1000, function () {
$('#wordsDiv').replaceWith('<img src = "images/letters/' + currentLetter + '.gif" />');
$('#wordsDiv').fadeIn(1000);
});
}
}
setTimeout(changeLetter, 1000);
}
animateLetters();
});
});