2016-11-03 30 views
0

我有一个页面,其中实时显示带有图像的事件流。由于它是实时的(事件发生时),因此它可能还没有完全可用,因为它仍然被上传到存储。JQuery延迟排队呼叫

调用来获得新的事件执行每两秒钟,每次调用可以返回多达20个事件(最新的20),但通常它是介于0和5

由于图像的问题可能不加载最初,onerror功能用于:

<img onerror="retryImage(this, 'imageUrl', 0)" src="imageUrl" /> 

function retryImage(source, url, attempts) { 
    img = new Image(); 
    img.src = url + '?' + (new Date()).getTime(); 
    img.onload = function() { 
     source.src = img.src; 
    }; 
    img.onerror = function() { 
     if (attempts > 4) { 
      source.src = 'not_found.png'; 
     } else { 
      source.src = 'loading.gif'; 
      attempts++; 
      $(this).delay(2000).queue(function() { 
       retryImage(source, url, attempts); 
       $(this).dequeue(); 
      }); 
     } 
    }; 
    return true; 
} 

的想法是尝试加载图像,如果失败,等待几秒钟,然后再试一次,最多5次。

不幸的是,在实践中每次偶尔(当多个图像同时初始加载失败时),其中一个显示的图像将属于不同的事件。这导致我认为我在滥用delay()queue()函数?

有什么想法?

回答

0

你确实是; delayqueue专门用于jQuery效果。从the documentation引述:

.delay()方法是最适合的jQuery排队效果 之间延迟。因为它是有限的 - 例如,它不提供一种方式来取消延迟 - .delay()不是替代JavaScript的原生 setTimeout函数,这可能更适合某些使用 的情况。

我相信这正是这样的用例!尝试是这样的:

function retryImage(source, url, attempts) { 
    img = new Image(); 
    img.src = url + '?' + (new Date()).getTime(); 
    img.onload = function() { 
    source.src = img.src; 
    }; 
    img.onerror = function() { 
    if (attempts > 4) { 
     source.src = 'not_found.png'; 
    } else { 
     source.src = 'loading.gif'; 
     attempts++; 
     setTimeout(function() { 
     retryImage(source, url, attempts); 
     }, 2000); 
    } 
    }; 
    return true; 
} 
+1

仅供参考 - 我标志着这个答案正确的,因为它根据的问题(我.delay的使用'()'和'.queue()')是正确的 - 但它并没有解决加载不正确图像的整体问题。这个问题是由于'img'变量是在全局而不是本地声明的(即'var img = new Image()')...愚蠢的疏忽! – user3282203