并发加载图片 并发数最大为n

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- <img src="https://akirajy.github.io/pokemonBook/static/gif/back-ef941d02.gif" alt=""> -->
<script>
/*
加载图片的最大并发数为 maxNum
每当有一张图片加载成功/失败,就腾出一个空位,可以加载剩余未加载的图片
所有图片加载完成后,结果按照加载顺序依次打出
*/

// 根据 url 加载图片
function loadImage(url) {
return new Promise((resolve, reject) => {
// new Image(width, height) 等价于 document.createElement('img)
const img = new Image(500, 500)
img.onload = () => {
console.log(`加载成功:${url}`);
resolve(img)
}
img.onerror = () => {
console.log(`加载失败:${url}`);
reject(new Error(`Error appears when loading ${url}`))
}
img.src = url
// 将 img 元素添加到 body 中
document.body.appendChild(img);
})
}

// 并发加载图片,maxNum 为最大并发数
async function multiLoadingImage(urls, maxNum) {
const executing = []
const res = []
const n = urls.length
for (url of urls) {
const p = loadImage(url)
res.push(p)
if (maxNum < n) {
const e = p.then(() => executing.splice(executing.indexOf(e), 1))
executing.push(e)
if (executing.length >= maxNum) {
await Promise.race(executing)
}
}
}
return Promise.all(res)
}

let urls = [
'https://t7.baidu.com/it/u=1595072465,3644073269&fm=193&f=GIF',
'https://t7.baidu.com/it/u=4198287529,2774471735&fm=193&f=GIF',
'https://t7.baidu.com/it/u=1956604245,3662848045&fm=193&f=GIF',
'https://t7.baidu.com/it/u=1956604245,3662848045&fm=193&f=GIF',
'https://t7.baidu.com/it/u=727460147,2222092211&fm=193&f=GIF',
'https://t7.baidu.com/it/u=3569419905,626536365&fm=193&f=GIF',
'https://t7.baidu.com/it/u=3911840071,2534614245&fm=193&f=GIF'
]
multiLoadingImage(urls, 3)
</script>
</body>
</html>

并发加载图片 并发数最大为n
http://example.com/2023/03/14/并发加载图片-并发数最大为n/
Author
John Doe
Posted on
March 14, 2023
Licensed under