I just encountered a very weird issue (I fixed it though) but I wanted to know why did it happen in the first place:
function stuffAppear() {
var i;
for (i = 0; i < speech.length; i++) {
apperance(i);
}
}
function apperance(i) {
var x = speech[i];
setTimeout(function() {$(speech[i]).fadeIn(1000); console.log(i);}, 1000 + i * 1500);
console.log(speech[i]);
}
The console log shows "#yo0" then "#ma0b" (which is the required) but at the same time, they never faded in
I played around with the code until I reached this:
function stuffAppear() {
var i;
for (i = 0; i < speech.length; i++) {
apperance(i);
}
}
function apperance(i) {
var x = speech[i];
setTimeout(function() {$(x).fadeIn(1000); console.log(i);}, 1000 + i * 1500);
}
And that did the trick, but I don't know why the first code didn't work. Can someone explain that to me, please? And thank you!
In a JSFiddle both versions work fine (and the same):
var speech = ["#yo0", "#ma0b", "#blah"];
function stuffAppear() {
var i;
for (i = 0; i < speech.length; i++) {
apperance(i);
}
}
function apperance(i) {
var x = speech[i];
setTimeout(function() {$(speech[i]).fadeIn(1000); console.log(i);}, 1000 + i * 1500);
console.log(speech[i]); // <<< THIS WOULD OCCUR IMMEDIATELY
}
var speech = ["#yo0", "#ma0b", "#blah"];
function stuffAppear() {
var i;
for (i = 0; i < speech.length; i++) {
apperance(i);
}
}
function apperance(i) {
var x = speech[i];
setTimeout(function() {$(x).fadeIn(1000); console.log(i);}, 1000 + i * 1500);
}
So I suspect what you are seeing is a side effect of your other code (not shown).
The only odd thing is you were logging in the first version twice (once outside the setTimeout which would display at the start - as you mentioned)
Having now seen the real code, the cause was changing of the speech
array during the timeouts. When the timeout function was finally hit the speech
array was empty!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With