Search code examples
jqueryimagedelay

Delay adding images to div in for loop


I want to add some time between adding the images to the element. This is my code :

    <script>
        var aantalkeergeklikt = 0;
        var uniekeid = 0;
        var pictures = ["../Spel in jQuery/img/bubbles/bom.png", "../Spel in jQuery/img/bubbles/green.png", "../Spel in jQuery/img/bubbles/red.png", "../Spel in jQuery/img/bubbles/yellow.png", "../Spel in jQuery/img/bubbles/orange.png", "../Spel in jQuery/img/bubbles/purple.png", "../Spel in jQuery/img/bubbles/blue.png"];
        var size = pictures.length

        for ( i = 0; i < 20; i++) {
            uniekeid = uniekeid + 1;
            var x = Math.floor(size * Math.random())

            var item = $("<img src='" + pictures[x] + "' alt='" + uniekeid + "' />").hide().delay("slow").fadeIn();
            $('#depionnen').append(item);
            console.log(item.alt);
        }

    </script>

At this point the delay is applied after adding all the images.

Can someone help me with this?


Solution

  • you have to use a setTimeout to delay a for loop.

    var i = 1;                     //  set your counter to 1
    
    function myLoop () {           //  create a loop function
       setTimeout(function () {    //  call a 3s setTimeout when the loop is called
          alert('hello');          //  your code here
          i++;                     //  increment the counter
          if (i < 10) {            //  if the counter < 10, call the loop function
             myLoop();             //  ..  again which will trigger another 
          }                        //  ..  setTimeout()
       }, 3000)
    }
    
    myLoop();                      //  start the loop
    

    Source

    So in your example it would be something like this:

    var i = 1;                     
    
    function myLoop () {           
       setTimeout(function () {    
          uniekeid = uniekeid + 1;
          var x = Math.floor(size * Math.random())
          var item = $("<img src='" + pictures[x] + "' alt='" + uniekeid + "' />").hide().delay("slow").fadeIn();
          $('#depionnen').append(item);
          console.log(item.alt);   
    
          i++;                     
          if (i < 20) {             
             myLoop();             
          }                        
       }, 3000)
    }
    
    myLoop();