简体   繁体   中英

Reload an image with setTimeout

when I load a image and loading fails, I try to reload after a delay using setTimeout , as below:

$('img').error(function(){
    setTimeout(function(){
        $(this).attr('src', $(this).attr('src') + '?' + Math.random());
    }, 3000);
});

But this solution doesn't reload the image as expected.

this is no longer referring to $("img") you need to assign a varialbe as a placeholder for this

$('img').error(function(){
    var $self = $(this);
    setTimeout(function(){
    $self.attr('src', $self.attr('src')+'?'+Math.random());
    }, 3000);
});

The value of this changes to window in your inner function scope. Save a reference to the jQuery wrapper of your image when the outer function is triggered.

$('img').error(function() {
    var $img = $(this);
    setTimeout(function(){
        $img.attr('src', $img.attr('src') + '?' + Math.random());
    }, 3000);
});

Edit:
As @epascarello pointed out, you're assuming there aren't any existing query params already on the image when you append ?randomNum . If you know that will always be the case, that's fine, although the param really should be ?key=randomNum . If it's possible that there are existing params, you'll have to do something similar to the below. ( But do you really need to append a random number to the URL? ).

function updatedSrc(oldSrc) {
    var delim = (oldSrc.indexOf('?') != -1) ? '&' : '?';
    return oldSrc + delim + "rand=" + Math.random();
}

And when you update the src you would do $img.attr('src', updatedSrc($img.attr('src'))) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM