Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda