-2

I have this script to load an image

function loadImage(URL) {
    var img = new Image();
    img.onerror = () => alert('image not found');
    img.src = URL;
}

loadImage("http://example.com/bar.jpg");

how can I retry a few times to load the image and then fail onerror?

btw. I´m using react. if there´s a way to do it with react. even better!

handsome
  • 2,335
  • 7
  • 45
  • 73

1 Answers1

1

You could try something like this

function loadImage(URL, retries = 5) {
    var img = new Image();
    img.onerror = () => {
      if (retries > 0){
        loadImage(URL, retries -1);
      } else {
        alert('image not found');
      }
    }
    img.src = URL;
}

loadImage("http://example.com/bar.jpg");
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317