Austin Burk
Austin Burk

Reputation: 960

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.

Upvotes: 8

Views: 16787

Answers (3)

jfriend00
jfriend00

Reputation: 707476

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");

Upvotes: 7

Yaniro
Yaniro

Reputation: 1587

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
);

Upvotes: 12

Emmanuel N
Emmanuel N

Reputation: 7449

Use window.stop to stop download

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

To change image source

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

Upvotes: 0

Related Questions