Javascript run a function inside a loop every x iterations

前端 未结 5 1444
借酒劲吻你
借酒劲吻你 2020-12-07 03:30

I have a variable of unknown value, it will be an integer. For this sake, lets say var a = 3;

I have a function that is called continuously:

<         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 04:25

    Here's an approach that encapsulates the counter, but uses a global variable for "a":

    var a = 3;
    
    function anim(){
        // Run the usual code here
        // ...
    
        if (++anim.counter % a === 0) {
            // Run the special code here
            // ...
        }
    }
    // Initialize static properties.
    anim.counter = 0;
    

    And here's an approach that encapsulates the "a" variable as well, referring to it as "frequency":

    function anim(){
        // Run the usual code here
        // ...
    
        if (++anim.counter % anim.frequency === 0) {
            // Run the special code here
            // ...
        }
    }
    // Initialize static properties.
    anim.counter = 0;
    anim.frequency = 1;
    

    Then set the desired frequency value before calling anim() for the first time:

    anim.frequency = 3;
    

提交回复
热议问题