Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel an image load after a period of time?

I need to be able to cancel an image load after a set period of time, and it needs to subsequently call the onError action.

What it will do:

Attempt to retrieve the resource. src="https://www.site.com/cgi-bin/pullimg.cgi?user=+encodeURI(document.cookie) , which pulls a user-specific resource. The cookies are stored in a protected folder.

If it can't in 1 second (1000 ms), then execute onError.

onError changes the images src attribute, then reloads the img. (Changes to different uri, like mirror.site.com/err.png)

Also, it can be a javascript function (newImage).

Sorry for not supplying existing code; I can code in multiple langs though.

like image 637
Austin Burk Avatar asked Dec 28 '11 17:12

Austin Burk


2 Answers

Try this:

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
);
like image 99
Yaniro Avatar answered Oct 22 '22 04:10

Yaniro


You can use this code to load an image and, if not successfully loaded within 1 second (whether the failure is via onerror, onabort or from the time elapsing), switch to load an alternate 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");
like image 29
jfriend00 Avatar answered Oct 22 '22 05:10

jfriend00