How to cancel image loading after a certain period of time?

I need to be able to cancel the image loading after a given period of time, and it needs to subsequently trigger the onError action.

What will he do:

An attempt to retrieve a resource. src = "https://www.site.com/cgi-bin/pullimg.cgi?user=+encodeURI(document.cookie), which retrieves a user-specific resource. Cookies are stored in a protected folder.

If it fails in 1 second (1000 ms), then run onError.

onError changes the src attribute of the images, then reloads img. (Changes in different uri, for example mirror.site.com/err.png)

Alternatively, it could be a javascript (newImage) function.

Sorry for not delivering existing code; I can code in several languages ​​though.

+3
source share
3 answers

You can use this code to download the image and, if it has not been successfully downloaded within 1 second (regardless of whether a failure occurred via onerror, onabort or from the expiration of time), switch to downloading an alternative image.

function loadImage(url, altUrl) {
    var timer;
    function clearTimer() {
        if (timer) {                
            clearTimeout(timer);
            timer = null;
        }
    }

    function handleFail() {
        // kill previous error handlers
        this.onload = this.onabort = this.onerror = function() {};
        // stop existing timer
        clearTimer();
        // switch to alternate url
        if (this.src === url) {
            this.src = altUrl;
        }
    }

    var img = new Image();
    img.onerror = img.onabort = handleFail;
    img.onload = function() {
        clearTimer();
    };
    img.src = url;
    timer = setTimeout(function(theImg) { 
        return function() {
            handleFail.call(theImg);
        };
    }(img), 1000);
    return(img);
}

// then you call it like this
loadImage("https://www.example.com/cgi-bin/pullimg.cgi?user=" + encodeURI(document.cookie), "http://mirror.site.com/err.png");
+4
source

Try the following:

var image = new Image();
image.src = "https://www.site.com/cgi-bin/pullimg.cgi?user=" + encodeURI( document.cookie );
setTimeout
(
    function()
    {
        if ( !image.complete || !image.naturalWidth )
        {
            image.src = "http://mirror.site.com/err.png";
        }
    },
    1000
);
+8
source

Use window.stop to stop loading

 if(window.stop !== undefined)
 {
    window.stop();
 }
 else if(document.execCommand !== undefined)
 {
 document.execCommand("Stop", false);
 }

To change the image source

 var img = document.getElementBYId("yourImageID");
 img.setAttribute("src","newSource.gif");
0
source

All Articles