Files
aladin-lite/_canvas/js/Downloader.js
2014-10-23 07:07:36 +00:00

87 lines
2.1 KiB
JavaScript

/******************************************************************************
* Aladin HTML5 project
*
* File Downloader
* Queue downloading for image elements
*
* Author: Thomas Boch[CDS]
*
*****************************************************************************/
Downloader = (function() {
var NB_MAX_SIMULTANEOUS_DL = 4;
// TODO : le fading ne marche pas bien actuellement
var FADING_ENABLED = false;
var FADING_DURATION = 700; // in milliseconds
var Downloader = function(view) {
this.view = view; // reference to the view to be able to request redraw
this.nbDownloads = 0; // number of current downloads
this.dlQueue = []; // queue of items being downloaded
this.urlsInQueue = {};
};
Downloader.prototype.requestDownload = function(img, url) {
// first check if url already in queue
if (url in this.urlsInQueue) {
return;
}
// put in queue
this.dlQueue.push({img: img, url: url});
this.urlsInQueue[url] = 1;
this.tryDownload();
};
// try to download next items in queue if possible
Downloader.prototype.tryDownload = function() {
while (this.dlQueue.length>0 && this.nbDownloads<NB_MAX_SIMULTANEOUS_DL) {
this.startDownloadNext();
}
};
Downloader.prototype.startDownloadNext = function() {
// get next in queue
var next = this.dlQueue.shift();
if ( ! next) {
return;
}
this.nbDownloads++;
var downloaderRef = this;
next.img.onload = function() {
downloaderRef.completeDownload(this, true); // in this context, 'this' is the Image
};
next.img.onerror = function() {
downloaderRef.completeDownload(this, false); // in this context, 'this' is the Image
};
next.img.src = next.url;
};
Downloader.prototype.completeDownload = function(img, success) {
delete this.urlsInQueue[img.src];
img.onerror = null;
img.onload = null;
this.nbDownloads--;
if (success) {
if (FADING_ENABLED) {
var now = new Date().getTime();
img.fadingStart = now;
img.fadingEnd = now + FADING_DURATION;
}
this.view.requestRedraw();
}
this.tryDownload();
};
return Downloader;
})();