Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!