Andy Evans
Andy Evans

Reputation: 7176

JQuery setTimeout not working in a loop

What I'm trying to do is create a quick and dirty slide show. The idea being that I have master div containing a blank "master" img tag and set of divs, each containing it's own img and a span tag. The source of each image is, in turn, set as the source of the master img. So I had started iterating through each image and tried to set it's source the master img's source with a setTimeout() and a 2 sec delay. The problem I'm having is that to code appears to wait for two seconds and only display the last image in the sequence.

$(document).ready(function () {
    $('div#slideshow').children('div.slideshowsourceimage').each(function () {
        var src = $(this).children('img').attr('src');
        var desc = $(this).children('span').text();

        setTimeout(function () {
            $('img#slideshowimage').attr('src', src);
        }, 2000);
    });
});

If I could get a second pair of eyes to help me find out what I'm doing wrong I'd appreciated it.

Thanks,

Upvotes: 0

Views: 843

Answers (2)

Paolo Bergantino
Paolo Bergantino

Reputation: 488374

I would do something like this:

$(function() {
    var $images = $('#slideshow div.slideshowsourceimage');
    var x = 0;
    setInterval(function() {
        if(x == $images.length) { // start over if we get to the last one
            x = 0;
        }

        var $cur = $images.eq(x);
        var src = $cur.find('img').attr('src');
        var desc = $cur.find('span').text();

        $('#slideshowimage').attr('src', src);
        x++;
    }, 2000);
});

Upvotes: 2

qw3n
qw3n

Reputation: 6334

You need to use setInterval or increment the number of seconds between each image showing. What is happening now is everything is registered to occur in two seconds and so only the last image shows. Something like

$(document).ready(function () {
    var time=0;
    $('div#slideshow').children('div.slideshowsourceimage').each(function () {
        var src = $(this).children('img').attr('src');
        var desc = $(this).children('span').text();

        setTimeout(function () {
            $('img#slideshowimage').attr('src', src);
            time+=2000;
        }, time);
    });
});

Upvotes: 1

Related Questions