延迟循环1秒

时间:2013-10-02 08:55:58

标签: javascript jquery loops delay settimeout

我需要每秒延迟一个循环,我需要计算循环迭代的次数,一旦它达到与长度相比可分为3,暂停一秒,然后继续循环。

DEMO http://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次。

我哪里错了? :(

2 个答案:

答案 0 :(得分: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整除时,它会在1000ms后再次调用myLoop函数并继续计数。

答案 1 :(得分: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();
相关问题