<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>test</title>
</head>
<body>
<script>
function downloadImage(url) {
// const img = new Image();
return new Promise((resolve) => {
// console.log(`開始下載: ${url}`);
const time = Math.random() * 3000; // 隨機模擬下載時間
// 模擬圖片下載
setTimeout(() => {
console.log(`下載完成: ${url}`);
resolve(`圖片數(shù)據(jù): ${url}`);
}, time);
});
// img.onload = () => {
// console.log(`下載完成: ${url}`);
// resolve(`圖片數(shù)據(jù): ${url}`);
// };
// img.onerror = () => {
// // 記錄錯誤
// errors[index] = new Error(`Failed to load image: ${url}`);
// resolve(); // 即使失敗也 resolve,保證流程繼續(xù)
// };
// img.src = url;
}
// 并發(fā)控制函數(shù)
async function downloadWithConcurrency(imageUrls, maxConcurrency = 3) {
// 下載完成結(jié)果
const results = [];
// 正在執(zhí)行下載的請求
const executing = new Set();
for (const url of imageUrls) {
// 如果達到最大并發(fā)數(shù),等待其中一個完成
if (executing.size >= maxConcurrency) {
await Promise.race(executing);
}
const promise = downloadImage(url).then((result) => {
results.push(result);
executing.delete(promise);
});
executing.add(promise);
}
// 等待所有剩余任務完成
await Promise.all(executing);
return results;
}
// 測試
const imageUrls = [
"image1.jpg",
"image2.jpg",
"image3.jpg",
"image4.jpg",
"image5.jpg",
"image6.jpg",
"image7.jpg",
"image8.jpg",
];
downloadWithConcurrency(imageUrls)
.then((results) => {
console.log("所有圖片下載完成:", results);
})
.catch((error) => {
console.error("下載出錯:", error);
});
</script>
</body>
</html>
時刻保持某個數(shù)量的并發(fā)下載請求
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。