2013-10-03 84 views
0

我正在尝试停止一个循环,以便其他事物可以运行,然后在序列中的正确时间再次返回循环。我的代码运行一次,但随后似乎是无法运行我用clearInterval();停止并启动setInterval()

function runPlanner() { 

    var plannerInterval = setInterval(function(){ 

     imageCounter++; 

     var imageTotal = $('li img').length; 

     if (imageCounter > imageTotal + 1) { 
      $('li img').hide(); 
      imageCounter = 0; 
      clearInterval(plannerInterval); 
     } else { 
      $('li img:nth-child(' + imageCounter +')').fadeIn('slow'); 
     } 

     console.log('image counter:',imageCounter); 
     console.log('image total:',imageTotal); 
    }, 2500); 

} 

后,然后我就可以开始运行这个,有:

runPlanner(); 

但是,如果条件满足,其中clearInterval被调用,然后使用该函数调用不起作用。任何想法,请!?

+0

所以,'runPlanner();'当你再次 – tymeJV

+0

复位调用它不工作'imageCounter' – okuznetsov

+1

@okuznetsov什么是'imageCounter = 0;'如果不进行重置呢? – George

回答

1

尝试使用setTimeout风格。所以你不会再遇到clearInterval的问题。

这样子。

function runPlanner() { 

     imageCounter++; 

     var imageTotal = $('li img').length; 

     if (imageCounter > imageTotal + 1) { 
      $('li img').hide(); 
      imageCounter = 0; 
     } else { 
      $('li img:nth-child(' + imageCounter +')').fadeIn('slow'); 

      // re-called `runPlanner` after 2500 sec 
      setTimeout(runPlanner, 2500); 
     } 

     console.log('image counter:',imageCounter); 
     console.log('image total:',imageTotal); 

} 

runPlanner(); 
+0

我刚刚意识到,这是因为我正在使用索引变量和第n个子变量。索引从0开始,第n个孩子从1开始!这会学到我! – JohnRobertPett