Can I run this nested functions in a better way?

javascript, jquery

Solution

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);

Problem

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); ```

Original source