JQuery and setTimeout inside a for loop

I ran into a very strange problem (although I fixed it), but I wanted to know why this happened 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 displays "# yo0", then "# ma0b" (which is required), but at the same time they never disappeared into

I played 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 this is a trick, but I do not know why the first code did not work. Can someone please explain this to me? And thanks!

+4
source share
1 answer

In JSFiddle, both versions work fine (and the same thing):

First: http://jsfiddle.net/TrueBlueAussie/Bkz55/3/

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
}

: http://jsfiddle.net/TrueBlueAussie/Bkz55/4/

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);
}

, , ( ).

, ( setTimeout, - )

:

, , speech -. - , speech !

+4

Source: https://habr.com/ru/post/1535226/


All Articles