andrew zabelo
andrew zabelo

Reputation: 23

Why are images not changing even though I changed the src?

I'm making a chess game using HTML and JS where a user can play against the computer. After every move, the image src for every square is changed to reflect the new position. However, when I call the function for the computer to move at the end of the user's move, the images only update after both moves have been made. I made sure that the image src was indeed changing, but it seems that the new images only load after all the tasks are done. Here is the relevant simplified code:

        function changeImages(){ 
            for(var x = 0; x < 64; x++){
                    console.log("image changed")
                       //getImage is an array containing the URLs for different pieces
                       //allPositions is a global array of the current positions of the game
                    document.getElementById("img" + x).src = getImage[allPositions[x]];
            }
        }

        function pressed(clicked_id) {
                playerMove(clicked_id)
                changeImages()
                engineMove()
                changeImages()
        }

        function playerMove(clicked_id){
            //user's move
        }

        function engineMove(){
            //computer's move
        }

In short, is there a way to ensure that a function executes only after the images have been changed?

Upvotes: 2

Views: 109

Answers (1)

Guerric P
Guerric P

Reputation: 31805

Yes, every HTMLImageElement has a onload event inherited from HTMLElement to which you can attach an event listener. Your code could look like this:

function changeImages(callback){
  Promise.all(allPositions.map(position => {
    document.getElementById("img" + x).src = getImage[position];
    return new Promise(resolve => document.getElementById("img" + x).addEventListener('load', resolve, { once: true }));
  })).then(callback);
}

function pressed(clicked_id) {
  playerMove(clicked_id, engineMove)     
}

function playerMove(clicked_id, callback){
  //user's move
  changeImages(callback)
}

function engineMove(){
  //computer's move
  changeImages()
}

Upvotes: 1

Related Questions