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:
<
Create a second variable which keeps hold of the current count, then wrap the call you only want every third iteration with
if(counter % a == 0) {
//code you want called
}
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!
You should check that your counter is greater than 0, or your function appendEnd
will be fired the first time:
if (counter > 0 && counter % a == 0) { ... }
In the following, the complete code:
var appendEndExecutedTimes = 0;
function anim(){
left = parseInt(galleryInner.css('left'), 10);
if(Math.abs(left) >= (galleryItem.length * galleryItem.width())){
galleryInner.css('left', 0);
}
galleryInner.animate({left: '-=20' }, 200, anim);
if (appendEndExecutedTimes > 0 && appendEndExecutedTimes % a === 0) {
that.appendEnd();
}
appendEndExecutedTimes += 1;
}
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;
Instantiate a counter variable that increments every time anim() is called. When
counter % a === 0
Then you run this.appendEnd()