Javascript 在jQuery.load()回调上设置超时

Javascript 在jQuery.load()回调上设置超时,javascript,jquery,Javascript,Jquery,我正在加载一个图像,其中包含有效图像和无效图像的处理程序: $('<img/>') .attr('src',$scope.newAssetData.newAssetUrl) .load(validImage) .error(invalidImage); $(' 我想在加载时设置一个超时。这意味着,如果一个图像需要超过t的时间来加载,那么做一些事情(例如,转到invalidImage处理程序) 有什么办法吗 谢谢,, Mila我想你应该这样使用超时,例如: var delay =

我正在加载一个图像,其中包含有效图像和无效图像的处理程序:

$('<img/>')  
.attr('src',$scope.newAssetData.newAssetUrl)
.load(validImage)
.error(invalidImage);
$('
我想在加载时设置一个超时。这意味着,如果一个图像需要超过t的时间来加载,那么做一些事情(例如,转到invalidImage处理程序)

有什么办法吗

谢谢,,
Mila

我想你应该这样使用超时,例如:

var delay = 1000, /* if image takes more than one second to load, call error handler */
    $img = $('<img/>').load(validImage)
        .error(invalidImage)
        .attr('src', $scope.newAssetData.newAssetUrl); /* set src after relevant events to hanlde older browsers cached src */
setTimeout(function () {
    if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
        $(this).off('load');
        invalidImage.call(this);
    }
}.bind($img[0]), delay);
$.ajax({
    url: [image src],
    timeout: [in milliseconds],
    type: "GET",
    success: function(response) {
        // I'm not sure what you'll be getting as your response
    },
    error: function(jqXHR, textStatus, errorThrown) {
    }
});
var delay=1000,/*如果映像加载时间超过1秒,请调用错误处理程序*/
$img=$('我认为您不能直接在
.load()
上设置超时

但是,如果您希望异步加载图像,那么可以将请求写出来,即使用
.ajax()
,然后设置超时

根据
.load()
的文档,“它有一个隐式回调函数”,因此您必须自己填充它

例如:

var delay = 1000, /* if image takes more than one second to load, call error handler */
    $img = $('<img/>').load(validImage)
        .error(invalidImage)
        .attr('src', $scope.newAssetData.newAssetUrl); /* set src after relevant events to hanlde older browsers cached src */
setTimeout(function () {
    if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
        $(this).off('load');
        invalidImage.call(this);
    }
}.bind($img[0]), delay);
$.ajax({
    url: [image src],
    timeout: [in milliseconds],
    type: "GET",
    success: function(response) {
        // I'm not sure what you'll be getting as your response
    },
    error: function(jqXHR, textStatus, errorThrown) {
    }
});

以下是.

也许这个主题会让你见鬼:你的问题显示研究很少。如果你使用jQuery,试着研究承诺或$。延迟。这里没有
load(handler);
on('load',handler)的缩写
要点-我会编辑我的帖子。但她仍然在异步加载图像,所以我的建议仍然有效。
异步加载图像
我真的不明白OP context的问题中这意味着什么?!@A.Wolff我想这与事实无关,我会删除它。我会从上面尝试你的解决方案。谢谢,这似乎是真的工作得很好!但我不明白setTimeout函数中的“this”是如何正确的对象。对我来说,现在它只是一个魔术。
.bind($img[0])
正在设置setTimeout回调中相关元素的上下文。搜索有关javascript绑定的文档,调用并应用方法