0

我有一个for loop并且我正在寻找路径。有用!但是,当我单击地图时,它的速度很快。我如何减慢for loop喜欢说......每个循环之间的一秒钟内发生的事情?

    for (i = 0; i < result.length; ++i) {

        var getCoords = new String(result[i]);
        var finalCoords = getCoords.split(",");
        var finalX = finalCoords[0];
        var finalY = finalCoords[1];

        currX = parseInt(x_block);
        currY = parseInt(y_block);

        moving = true;

        realSpawnX = finalX * 32;
        realSpawnY = finalY * 32;

        context.drawImage(playerImg, realSpawnX, realSpawnY, 32, 32);
    }
4

2 回答 2

3
function loop(i) {
  ++i;

  your code

  if (i < result.length) {setTimeout("loop("+i+")", 1000); }
}

在某个时候开始循环:

loop(0);

更新:

jsfiddle 上的示例

更新 2:

定义辅助函数循环

function loop(i, result_length, payload) {
  if (i < result_length) {
    payload(i);
    ++i;          
    setTimeout(function() {loop(i, result_length, payload);} , 2000);
  }
}

然后在原始循环的位置这样调用:

         loop(0, result.length, function(i) {
                getCoords = new String(result[i]);
                finalCoords = getCoords.split(",");
                finalX = finalCoords[0];
                finalY = finalCoords[1];

                currX = parseInt(x_block);
                currY = parseInt(y_block);

                moving = true;

                realSpawnX = finalX * 32;
                realSpawnY = finalY * 32;
                context.drawImage(playerImg, realSpawnX, realSpawnY, 32, 32);
                console.log("Step taken...");
          });
于 2012-05-02T23:38:04.610 回答
1

试试这个:

function funcName(counter, end){
    if(counter < end){
        var getCoords = new String(result[i]);
        var finalCoords = getCoords.split(",");
        var finalX = finalCoords[0];
        var finalY = finalCoords[1];

        currX = parseInt(x_block);
        currY = parseInt(y_block);

        moving = true;

        realSpawnX = finalX * 32;
        realSpawnY = finalY * 32;

        context.drawImage(playerImg, realSpawnX, realSpawnY, 32, 32);

        setTimeout(function(){
            funcName(counter+1, end);
        },1000);
    }
    else{
        movingBlocked=false;
    }
}

//use it like this
movingBlocked = true;
funcName(0, result.length);
while(movingBlocked){
    ;//do nothing
}

这是它的一个小提琴http://jsfiddle.net/qcaYh/

更新

添加全局和忙碌等待以保持代码同步。这具有在等待移动完成时暂停的效果。

//全局变量movingBlocked = false;

于 2012-05-02T23:48:00.840 回答