Please explain how you can hang a class on each element of the array at a certain interval?

$(function() { $array = $('.array-item'); setTimeout(function() { $array.each(function() { setTimeout(function() { $(this).addClass('red'); }, 300); }); }, 1000); }); 
 div { display: block; width: 100px; height: 50px; padding: 15px; background-color: green; font-size: 20px; line-height: 20px; text-align: center; } div.red { background-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="array-item">1</div> <div class="array-item">2</div> <div class="array-item">3</div> 

then I want a second after the page loads, the green blocks turn red in turns with an interval of 300ms. If possible, I would like to see a solution on both JS and JQ. Thank you in advance))

PS and please indicate why my code does not work)))

    2 answers 2

    First, your example does not work because the function you shove into the timer contains its own this . You must either add a .bind(this) , or use a lambda function . moreover - in your example everything gets over and put on a timer - the script does not wait until the previous block is painted and just throws its own timer. Implement as you need, you can do something like this:

     $(function() { $array = $('.array-item'), lastIndex = 0; setTimeout(setItemColor, 300); function setItemColor () { jQuery($array[lastIndex]).addClass("red"); lastIndex += 1; if ($array.hasOwnProperty(lastIndex)) setTimeout(setItemColor, 300); }; }); 
     div { display: block; width: 100px; height: 50px; padding: 15px; background-color: green; font-size: 20px; line-height: 20px; text-align: center; } div.red { background-color: red; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="array-item">1</div> <div class="array-item">2</div> <div class="array-item">3</div> 

      Something you too smart

       $(function() { $current = $('.array-item').first(); function changeColor() { $current.addClass('red'); $current = $current.next(); setTimeout(changeColor, 300); } setTimeout(changeColor, 300); }); 
       div.array-item { display: block; width: 100px; height: 50px; padding: 15px; font-size: 20px; line-height: 20px; text-align: center; background-color: green; } div.red { background-color: red; } 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <div class="array-item">1</div> <div class="array-item">2</div> <div class="array-item">3</div> </div> 

      • no, I didn’t think too much)) the fact of the matter is that I need the blocks to be painted one by one at intervals, and not all at once - Sergey Kanyukov
      • @SergeyKanyukov, corrected. +1 to the solution. But the principle is the same as the answer above - ArchDemon