Skip to content Skip to sidebar Skip to footer

Update Global Variable From Jquery Nested Function

I have a problem with this piece of code: var elements; var current = 100; $(document).ready(function() { elements = = $('.slide').length; iterate(); }); functio

Solution 1:

If this line is invoked before the DOM is ready, .length is 0:

var elements = $('.slide').length;

Which means the condition for this if will always be true:

if (++current >= elements) { current = 0; }

You can fix it like this:

var elements;
var current = 100;

$(document).ready(function() {
    elements = $('.slide').length;
    iterate();
});

Also, this is a little bit of an odd use of .queue(). There's nothing that needs queueing.

I'd rework it like this:

function iterate() {
    var slide = $('.slide').eq(current).hide();
    if (++current >= elements) { current = 0; }
    $('.slide').eq(current).show();

    // Call this function again after the specified duration
    setTimeout(iterate, 1000);
}

Post a Comment for "Update Global Variable From Jquery Nested Function"