Skip to content

Instantly share code, notes, and snippets.

@1franck
Last active January 27, 2017 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1franck/4fa68facc9bdce2a880fcacf5f4c2b90 to your computer and use it in GitHub Desktop.
Save 1franck/4fa68facc9bdce2a880fcacf5f4c2b90 to your computer and use it in GitHub Desktop.
Check if an image is loaded after x attempt(s) of x ms each
function ImageLoader(url, callback, attempt_count, attempt_interval) {
var $this = this,
callback = callback,
src = url,
attempt = 0,
attempt_count = attempt_count || 5,
attempt_interval = attempt_interval || 500,
loaded = false,
intervalInstance;
var img = new Image();
img.onload = function() {
loaded = true;
}
img.src = src;
var intervalInstance = setInterval(function() {
if(attempt_count < attempt) {
++attempt;
}
else {
clearInterval(intervalInstance);
callback(loaded, img);
}
}, attempt_interval);
}
@1franck
Copy link
Author

1franck commented Jan 27, 2017

How to use:

var myimage = new ImageLoader( "http://example.com/myimage.jpg",  function(loaded, img) {
        if(loaded) {
            console.log('Image loaded');
            console.log(img);
        }
        else {
            console.log('Image fail');
        }
    },
    6, // = number of attempts
    500 // = duration in ms of an attempt
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment