Javascript run a function inside a loop every x iterations

前端 未结 5 1453
借酒劲吻你
借酒劲吻你 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:22

    Well firstly you will need an incrementing variable counting how many times the function has been called. For instance, start your function with this:

    var me = arguments.callee;
    me.timesCalled = (me.timesCalled || 0)+1;
    

    Now, you can check that counter. To see that something happens "every X times", simply check to see if the modulus by X is 0:

    if( me.timesCalled % a == 0) { /* do something */ }
    

    And there you have it!

提交回复
热议问题