Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I run this nested functions in a better way?

I was just wondering if I could run this functions in a better way, I mean I don't like the collection of functions in there :

setTimeout(function() {
        $(self.header_buttons_classes[0]).addClass(self.animations[15]);
        setTimeout(function() {
            $(self.header_buttons_classes[1]).addClass(self.animations[15]);
            setTimeout(function() {
                $(self.header_buttons_classes[2]).addClass(self.animations[15]);
                setTimeout(function() {
                    $(self.header_buttons_classes[3]).addClass(self.animations[15]);
                    setTimeout(function() {
                        $(self.header_buttons_classes[4]).addClass(self.animations[15]);
                        setTimeout(function() {
                            $(self.header_buttons_classes[5]).addClass(self.animations[15]);
                        }, 500);
                    }, 500);
                }, 500);
            }, 500);
        }, 500);
    }, 500);
like image 310
Roland Avatar asked Jun 05 '12 14:06

Roland


1 Answers

In addition to setTimeout there is also the setInterval function which allows you to run code every X milliseconds. You could simplify your code as follows:

var i = 0;
var total = self.header_buttons_classes.length;
var x = setInterval(function() {
    if(i == total) {
        clearInterval(x);
    } else {
        $(self.header_buttons_classes[i]).addClass(self.animations[15]);
        i++;
    }
}, 500);
like image 72
Paolo Bergantino Avatar answered Sep 29 '22 20:09

Paolo Bergantino