Matt D. Webb
Matt D. Webb

Reputation: 3314

jquery delay function with IF statement

Can anyone tell me why my IF statement is firing before updating the UI with the each loop?

The code basically wants to delay adding css classes to the UI then once each one has been added, redirect the user. It currently just directs immediately?!

$("#logo").click(function() {

    //define variables:
    var eventDuration = 500;
    var elementArray = ['ribbon', 'left-panel', 'wid-id-1', 'wid-id-2'];
    var animationArray = ['slideOutRight', 'slideOutLeft', 'rotateOutUpRight', 'rotateOutUpRight'];

    //Loop through elements and update UI with timer function:
    $.each(elementArray, function(index, value) {

        //Increments the delay of the element updates:
        var delaytimer = index * eventDuration + eventDuration;

        //Adds animation css classes to onpage elements:
        $('#' + value).delay(delaytimer).queue(function() {
            $(this).addClass('animated ' + animationArray[index]).dequeue();
        });

        //Once complete redirect to the home page:
        if (index === 3) {
            $(this).delay(delaytimer + 500).queue(function() {
                window.location.replace('/').dequeue;
            });
        }

    });
});

Upvotes: 0

Views: 2396

Answers (1)

Evan Knowles
Evan Knowles

Reputation: 7511

Your if statement is being executed immediately because it isn't inside the delay function. Try moving it in there.

$('#' + value).delay(delaytimer).queue(function() {
        $(this).addClass('animated ' + animationArray[index]).dequeue();


       //Once complete redirect to the home page:
       if (index === 3) {
            $(this).delay(delaytimer + 500).queue(function() {
               window.location.replace('/').dequeue;
           });
       }
    });

Upvotes: 2

Related Questions