使用javascript在循环内设置超时



我正在制作一个解谜函数,它使用当前打乱顺序的一组拼图。每个片段都有一个id,该id指向数组中的正确位置。我在即将交换的单品上设置了叠加颜色。我希望在上色和交换之间有一个延迟。

function solvePuzzle() {
while (rezolvat == false) // while all pieces are not in correct position
for (var i = 0; i < _piese.length; i++) { // iterates through array of puzzle pieces
if (checkPiesa(i) == false) {
_piesaCurentaDrop = _piese[i];
_piesaCurenta = getPiesaDestinatie(_piesaCurentaDrop.id); // destination piece
_context.save();
_context.globalAlpha = .4;
_context.fillStyle = PUZZLE_HOVER_TINT;
_context.fillRect(_piesaCurentaDrop.xPos, _piesaCurentaDrop.yPos, _latimePiesa, _inaltimePiesa);
_context.fillStyle = PUZZLE_DESTINATION_HOVER_TINT;
_context.fillRect(_piesaCurenta.xPos, _piesaCurenta.yPos, _latimePiesa, _inaltimePiesa);
_context.restore();
// here I want to have some kind of 'sleep' for 2000 ms so you can see the pieces about to be swapped
dropPiece(); // function for swapping puzzle pieces
}
}
}

您可以使用javascript的setTimeout()函数,这些函数将在指定的毫秒后执行该函数,您可以在这里了解更多信息

function solvePuzzle() {
while (rezolvat == false) // while all pieces are not in correct position
for (var i = 0; i < _piese.length; i++) { // iterates through array of puzzle pieces
(function (i) {
setTimeout(function () {
if (checkPiesa(i) == false) {
_piesaCurentaDrop = _piese[i];
_piesaCurenta = getPiesaDestinatie(_piesaCurentaDrop.id); // destination piece
_context.save();
_context.globalAlpha = .4;
_context.fillStyle = PUZZLE_HOVER_TINT;
_context.fillRect(_piesaCurentaDrop.xPos, _piesaCurentaDrop.yPos, _latimePiesa, _inaltimePiesa);
_context.fillStyle = PUZZLE_DESTINATION_HOVER_TINT;
_context.fillRect(_piesaCurenta.xPos, _piesaCurenta.yPos, _latimePiesa, _inaltimePiesa);
_context.restore();
// here I want to have some kind of 'sleep' for 2000 ms so you can see the pieces about to be swapped
// setTimeout in side task execution
setTimeout(() => dropPiece(), 1000); // function for swapping puzzle pieces
}
}, 2000 * i); // schedules excution increasingly for each iteration
})(i);
}
}

然而,在上面的代码中,循环会立即结束,它会使用setTimeout在指定的增加时间(i*2000(后调度每次迭代的执行

因此执行,(尽管循环立即完成(

第一次迭代将在0*2000=0毫秒时立即开始,

第二次执行的任务将在(1*2000(之后执行,

第三次执行的任务将在(2*2000(之后执行,

等等。

为了简单理解,请查看下面的示例代码

工作代码示例

for (var i = 0; i < 5; i++) {
(function(i) {
setTimeout(function() {
console.log(i);
setTimeout(() => console.log(i + 0.5), 1000); // setTimeout in side task execution in case needed
}, 2000 * i); // schedules excution increasingly for each iteration
})(i);
}

相关内容

  • 没有找到相关文章

最新更新