I\'d like to cancel a .load() operation, when the load() does not return in 5 seconds. If it\'s so I show an error message like \'sorry, no picture loaded\'.
What I
I don't think you can get there from here - as @Pointy mentioned, you need to need to get to the XmlHttpRequest object so you can access the .abort()
method on it. For that, you need the .ajax()
jQuery API which returns the object to you.
Barring the ability to abort the request, another method to consider is to add knowledge of the timeout into the callback function. You could do this two ways - first:
var hasImage = false;
$('#errorMessage')
.idle(5000, function() {
if(!hasImage) {
// 1. cancel .load()
// 2. show error message
// 3. Add an aborted flag onto the element(s)
$('#myImage').data("aborted", true);
}
});
And your callback:
$('#myImage')
.attr('src', '/url/anypath/image.png')
.load(function(){
if($(this).data("aborted")){
$(this).removeData("aborted");
return;
}
hasImage = true;
// do something...
});
Or you could bypass the idle for this particular functionality:
$('#myImage')
.attr('src', '/url/anypath/image.png')
.data("start", (new Date()).getTime())
.load(function(){
var start = $(this).data("start");
$(this).removeData("start");
if(((new Date()).getTime() - start) > 5000)
return;
hasImage = true;
// do something...
});
Neither approach is ideal, but I don't think you can directly cancel load as of jQuery 1.4 - might be a nice feature request to the jQuery team, though.