The problem is that in the function in setTimeout, array_one[a] == undefined

 function timeStart() { var array_one = new Array("#bmw1", "#bmw2", "#bmw3", "#bmw4", "#bmw5"); var array_two = new Array("#mercedes1", "#mercedes2", "#mercedes3", "#mercedes4", "#mercedes5") for (var a = 0, b = 1000; a < 5; ++a, b += 2000) { setTimeout(function () { $(array_one[a] + "," + array_two[a]).fadeOut(1000, function () { $(array_one[a + 1] + "," + array_two[a + 1]).fadeIn(3000) }) } , b) } } 

    2 answers 2

    Simplify the question to this:

     <html> <head> <script type="text/javascript"> var z = new Array("1", "2", "3"); for (var i = 0; i < 3; i++) { setTimeout(function () { alert(z[i]); }, 1000); } </script> </head> <body> </body> </html> 

    Why doesn't it work (alert shows undefined)? Because at the moment of calling i = 3, the cycle has already ended, and the value of the array is taken beyond its boundaries.

    Adding .

    How to do right? It is necessary to transfer argument to the function.

     var z = new Array("1", "2", "3"); for (var i = 0; i < 3; i++) { setTimeout(function (i) { alert(z[i]); }(i), 1000); } 
    • Yes, I already understood this, how can I write the rules that I want - ZoZexZero
    • Completed the answer. - Nicolas Chabanovsky
    • Why produce one and tighter thread on the forum? - nikita_sergeevich February
    • @NicolasChabanovsky - Has anyone run this? - Igor

    reassign the variable b in the loop and use the new variable already as a parameter for the time interval.

     function timeStart() { var array_one = new Array("#bmw1", "#bmw2", "#bmw3", "#bmw4", "#bmw5"); var array_two = new Array("#mercedes1", "#mercedes2", "#mercedes3", "#mercedes4", "#mercedes5") for (var a = 0, b = 1000; a < 5; ++a, b += 2000) { set t=b; setTimeout(function () { $(array_one[a] + "," + array_two[a]).fadeOut(1000, function () { $(array_one[a + 1] + "," + array_two[a + 1]).fadeIn(3000) }) } , t) } } 

    It may also be necessary to reassign the variable a . So terrible this setTimeout .

     function timeStart() { var array_one = new Array("#bmw1", "#bmw2", "#bmw3", "#bmw4", "#bmw5"); var array_two = new Array("#mercedes1", "#mercedes2", "#mercedes3", "#mercedes4", "#mercedes5") for (var a = 0, b = 1000; a < 5; ++a, b += 2000) { set t=b; set mas=a; setTimeout(function () { $(array_one[mas] + "," + array_two[mas]).fadeOut(1000, function () { $(array_one[mas + 1] + "," + array_two[mas + 1]).fadeIn(3000) }) } , t) } } 
    • does not help, there is still an error due to the seTimeOut in the loop + animation with time is set - ZoZexZero