如何在循环中第一次调用函数

时间:2016-10-25 10:15:51

标签: jquery velocity.js

这里我有一组将继续循环的动画,我试图仅在第一次迭代时调用该函数,当第一次迭代结束时,不再调用该函数。我怎么能这样做?

这是我的代码

             var r5anim1 = function(){
                $(".r5").velocity({ 
                      opacity: 1,
                      scale: [1,0],
                    }, {
                    duration:300,
                    complete: function() {
                    r5anim2();
                    }
                });
             }  

            var r5anim2 = function(){
                $(".r5").velocity({ 
                  opacity: 0,
                },{
                    duration:200,
                    complete: function() {
                    r6anim1();
                    wishes() // here i have called the function which should execute only on first loop.
                }               
            });
            }

            var r6anim1 = function(){
                $(".r6").velocity({ 
                      opacity: 1,
                      scale: [1,0],
                    }, {
                    duration:300,
                    complete: function() {
                    r6anim2();
                    }
                });
             }  

            var r6anim2 = function(){
                $(".r6").velocity({ 
                  opacity: 0,
                },{
                    duration:200,
                complete: function() {                                         
                    r5anim1();       //on end this will start the loop again 
                }               
            });
            }




        /*****************this function should be called only for the first time******************/
        var wishes = function(){
            boolvalue = 0;
            $(".wishes").velocity({ 
                  opacity: 1,
                  scale: [1,0.4],
                }, {
                duration:600,
            });
         }  
        r5anim1();

2 个答案:

答案 0 :(得分:1)

创建全局变量

var isTriggered = false;

测试ifTriggered,如果它不是tigger调用函数

if(!isTriggered)
 {
wishes()
}

在wishes()函数中将变量更改为true,以便循环停止

function wishes() {
isTriggered = false;
//other code
}

答案 1 :(得分:0)

您必须创建一个可全局访问的变量,并将其默认为false

var isFunctionCalled = false;

仅当标志为false时调用该函数,并在调用函数时将标志更改为true。

if(isFunctionCalled == false){
    wishes()
    isFunctionCalled = true;
}