Skip to content Skip to sidebar Skip to footer

How To Delay A For Loop In Jquery

I am trying to make a image gallery and i am using a for loop to load all the images. but now I have the problem that it is going fast so I want to delay the the loop each time. I

Solution 1:

instead of using a for loop you may use a recursive function

var src = 'img/nature/';
 var img = ['1.jpg'];
 var image = [ "1.jpg", "2.jpg", "3.jpg",'4.jpg','5.jpg','6.jpg','7.jpg' ];
 var i = 0;
 var showGallery = function(){
    $('#frame').append('<img class="tile hide" src="'+src + image[ i ]+ '">');
    $('.hide').show(500);
    i++;
    if (i<image.length){
        setTimeout(showGallery,500);
    }
 };

 if (image.length > 0){
    showGallery();
 }

Solution 2:

You can also try this:

functiontest() {
    var src = 'img/nature/';
    var img = ['1.jpg'];
    var image = [ '1.jpg', '2.jpg', '3.jpg','4.jpg','5.jpg','6.jpg','7.jpg' ];

    setInterval(function() {
         $.each(image, function(index, value) {
            $('#frame').append('<img class="tile hide" src="'+src + value + '">');
            $('.hide').show(500);
         });
    }, 500);
}

Change 500 at end to whatever...

But I suspect this is not what you want to do... The approach below might be what you want:

functiontest() {
    var src = 'img/nature/',
        img = ['1.jpg'],
        image = [ '1.jpg', '2.jpg', '3.jpg','4.jpg','5.jpg','6.jpg','7.jpg' ],
        maxIndex = (image.length - 1),
        cIndex = 0;

    setInterval(function() {
        if (cIndex == maxIndex)
            cIndex = 0;
        $('#frame').append('<img class="tile hide" src="'+src + image[cIndex] + '">');
        $('.hide').show(500);
        cIndex++;
    }, 500);
}

Solution 3:

Your slideshow is for only 500 milliseconds. Increase that value at

setTimeout(function(){ },500); to have delay in slideshow.

& call the function test inside the loop...so that the slideshow continues.

sample:

function slideit(){

if (!document.images)
return0document.images.slide.src=eval("image"+step+".src")
if (step<3)
step++
else
step=1setTimeout("slideit()",3000)

}

Solution 4:

Another solution is to use a temporary scope with increasing time values for the timeout events..

functiontest(){
    var src = 'img/nature/';
    var img = ['1.jpg'];
    var image = [ "1.jpg", "2.jpg", "3.jpg",'4.jpg','5.jpg','6.jpg','7.jpg' ];
    for ( var i = 0; i < image.length; i++ ) {
        (function(i){
            setTimeout(function(){
                $('#frame').append('<img class="tile hide" src="'+src + image[ i ]+ '">');
                $('.hide').show(500);
            }, 500*i);
         })(i);
    }
}

Post a Comment for "How To Delay A For Loop In Jquery"