Open Rain120 opened 2 years ago
function limitLoad(list, callback, limit) {
const queue = list.slice();
const promises = queue.splice(0, limit).map((url, index) => {
return callback(url).then(() => {
return index;
});
});
let p = Promise.race(promises);
queue.forEach((url, index) => {
p = p.then((res) => {
promises[res] = callback(url).then(() => {
return res;
});
return Promise.race(promises);
});
});
}
const loadImg = (url, callback) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
resolve(img);
}
img.onerror = () => {
reject(new Error('load error'));
}
img.src = url;
callback(img);
});
}
同时下载的链接不超过 3 个的情况下,尽可能快地完成。