2012-06-25 164 views
0

我有一個未知值的變量,它將是一個整數。對於這個份上,可以說var a = 3;Javascript每循環運行一次循環內的函數

我有一個被稱爲連續函數:

var a = 3; 
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); 

     that.appendEnd(); 
} 

我想運行this.appendEnd()每3次而已,因爲a === 3

我該怎麼做?

+0

沒有看到'此代碼 –

回答

5

實例化每次調用anim()時遞增的計數器變量。當

counter % a === 0 

然後運行this.appendEnd()

+0

該變種了',我是太慢了打字。 –

1

那麼首先你需要一個遞增變量計數功能已多少次被調用。例如,用這個開始你的功能:

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

現在,你可以檢查該計數器。要看到「每X次」會發生什麼情況,只需檢查X的模數是否爲0即可:

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

並且您擁有它!

1

創建這使保持當前計數的第二個變量,然後再包你只想與

if(counter % a == 0) { 
    //code you want called 
} 
0

每次第三次迭代調用你應該檢查你的計數器大於0,或者你的函數appendEnd會被解僱的第一次:

if (counter > 0 && counter % a == 0) { ... } 

在下文中,完整的代碼:

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; 

    } 
0

下面是封裝了計數器的方法,但使用全局變量「一」:

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; 

下面是一個封裝了「一個」變量以及一種方法,將其稱爲「頻率」:

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; 

調用動畫()首次在此之前設定所需的頻率值:

anim.frequency = 3;