lundi 4 novembre 2019

Setting timeout inside loop with javascript

I'm making a puzzle solving function which uses an array of puzzle pieces in their current shuffled order. Each piece has an id which points to the correct position in the array. I set overlay colors on the pieces that are about to be swapped. I want for there to be a delay between the pieces being colored and then swapped.

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
            }
        }
}



Aucun commentaire:

Enregistrer un commentaire