Infinite loop with image.onload and image.onerror
javascript
Solution
The problem is that you re-assign the `successUrl` repeatedly in your `onload` callback, causing infinite recursion because it gets called over and over again.
To solve, update the `onload` callbacks:
img.onload = function() {
this.onload = function() {
// Whatever you want to do now.
};
this.src = successUrl;
};
(The same with the error callback).
In general, I don't think this is a clean way of doing it. I would simply create multiple `Image` objects to avoid confusion (and possibly preload the spinner with the page). Allocating `Image` has only tiny overhead and almost never matters.
Problem
I'm trying to load and image and if the url is not valid, put an error image instead. In my case the onerror event seem to be called infinitely: html: ``` <div id="output"></div> ``` javascript: ``` function createImage(imageId) { var spinnerUrl = 'http://placehold.it/600&text=spinner'; var errorUrl = 'http://placehold.it/600&text=error'; var successUrl = 'http://placehold.com/600&text=success'; var img = new Image(); img.onerror = function() { console.log('no image at url: ' + imageId); this.src = errorUrl; }; img.onload = function() { this.src = successUrl; }; img.src = spinnerUrl; return img; }; function loadImage(id) { document.getElementById(id).appendChild(createImage('image-id')); }; loadImage('output'); ``` you'll notice that the log displays 'no image at url: image-id'