2013-10-02 217 views
0

我需要每秒延迟一个循环,我需要计算循环迭代了多少次,一旦它的长度与可分割长度相比,暂停一秒,然后继续循环。延迟循环1秒

DEMOhttp://jsfiddle.net/eR6We/1/

var callsPerSecond = 500; 
var len = 1900; 
var delay = 1000; 

var i = 1; // set your counter to 1 

function myLoop() { // create a loop function 
    setTimeout(function() { // call a 3s setTimeout when the loop is called 
     $('#log').append('<li>called</li>'); // your code here 
     i++; // increment the counter 
     if (i < ((len - (i % callsPerSecond))/callsPerSecond)) { // if the counter < 10, call the loop function 
      myLoop(); // .. again which will trigger another 
     } // .. setTimeout() 
     console.log('foo' + i); 
    }, 500) 
} 

myLoop(); 

所以我应该得到1900 FOOS在我的日志,与第二的延迟,3次因为1900是500的3倍divisable。

我哪里错了? :(

回答

1

此代码你想要做什么:

var callsPerSecond = 500; 
var len = 1900; 
var delay = 1000; 

function myLoop (i) 
{ 
    while(i < len) 
    { 
     i++; 
     console.log('foo' + i); 
     if(i % callsPerSecond == 0) 
     { 
      setTimeout(function() { myLoop(i); }, delay); 
      break; 
     } 
    } 
}; 

myLoop(0); 

当我是callsPersecond整除,它1000毫秒之后再次调用myLoop功能并继续计数

1

如果我明白你的问题,它是你的解决方案

var callsPerSecond = 500; 
var len = 1900; 
var delay = 1000; 
var i = 1; // set your counter to 1 

function myLoop() { // create a loop function 
    setTimeout(function() { // call a 3s setTimeout when the loop is called 

     if (i < ((len - (i % callsPerSecond))/callsPerSecond)) { // if the counter < 10, call the loop function 
      $('#log').append('<li>called</li>'); // your code here 

     } // .. setTimeout() 

     myLoop(); // .. again which will trigger another 
     console.log('foo' + i); 
     i++; // increment the counter 
    }, delay) 
} 

myLoop(); 
+0

Thankyou为你的回应,它确实工作,但Ruudts回答是一个更好的眼睛:) –