Adam
Adam

Reputation: 832

jQuery loading bar loop

I am trying to create a loading bar that animates for 5 seconds and when its finished it goes back to the begining and continiously loops

On the example below I've kind of got it working but sometimes when the bar is fully loaded there is a long pause before going back to the begining and starting again, does anyone know how to fix this or perhaps a better way of doing it?

load();

function load() {

    $('.progress div').animate({
        width: '100%'
    }, 5000, load);

    setTimeout(function () {
        $('.progress div').animate({
            width: '0%'
        }, 1, load);
    }, 5000);
}

http://jsfiddle.net/7jtFS/

Upvotes: 1

Views: 203

Answers (2)

Banana
Banana

Reputation: 7483

may i suggest a different approach?

you could alternate between two functions where one would fill the bar and one would reset it while both call the other one when they are done:

Example

js:

Step1Fill();

function Step1Fill(){
    $('.progress div').animate({
            width: '100%'
    }, 5000).promise().done(function(){
        Step2Reset();
    });
}
function Step2Reset(){
    $('.progress div').css({
        width:'0%'
    });
    Step1Fill();
}

Upvotes: 1

chemitaxis
chemitaxis

Reputation: 14937

Try this:

load();

function load() {


    $('.progress div').animate({
        width: '100%'
    }, 5000, function() {
// Animation complete.

    $('.progress div').width(0)
    load();            

    });


}

Fiddle Link

Upvotes: 1

Related Questions