我可以更好地运行这个嵌套函数吗?

时间:2022-12-02 01:06:48

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

1 个解决方案

#1


6  

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:

除了setTimeout,还有setInterval函数,它允许您每X毫秒运行一次代码。您可以将代码简化如下:

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

#1


6  

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:

除了setTimeout,还有setInterval函数,它允许您每X毫秒运行一次代码。您可以将代码简化如下:

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