Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
JS : callback function is called when image is loaded but in fact image.complete shows it's not loaded

Hi everyone and Happy New Year,

I'm working on a small game project using JavaScript and I encountered a problem when loading images.
I want all the images to be loaded before I display them so I created a map in which each image is linked to false, and when the image is loaded, an event listener calls a function which set the image to true in my map.
But sometimes, my map is full of true without any image on my screen and when I print img.complete it's false, meaning it's not loaded.
Everything here is in a class of my file and this.chargementImg is the map.

Here is the image loading function:

chargerImage(chemin)
    {
        let img = new Image();
        this.chargementImg.set(chemin, false);
        img.addEventListener("load", this.updateChargementImg(chemin));
        img.src = chemin;
        return img;
    }

And the callback function:

updateChargementImg(chemin)
    {
        this.chargementImg.set(chemin, true);
    }

Console output when no images shown:

Map(3) {'./elements/images/fonds/sol/DarkSpace.png' => true,
'./elements/images/fonds/mur/Castle2.png' => true,
'./elements/images/ennemies/Earthspirit.png' => true}

img1.complete : false
img2.complete : false
img3.complete : false

I don't understand why it's not working. Thanks for your answers.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Make the load EventListener an unnamed function. Inside that put the updateChargementImg and return img. There will then be no race or async.

img.addEventListener("load", function(){
 this.updateChargementImg(chemin);
  return img;
});
img.src = chemin;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda