我有一个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);
}
答案 0 :(得分:3)
function loop(i) {
++i;
your code
if (i < result.length) {setTimeout("loop("+i+")", 1000); }
}
在某些时候开始循环:
loop(0);
<强>更新强>
更新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...");
});
答案 1 :(得分: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/
<强>更新强>:
添加全局和忙碌等待以保持代码同步。这会在等待移动完成时暂停。
//全球 var movingBlocked = false;