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> <script>
function loadImage(url) { return new Promise((resolve, reject) => { 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 document.body.appendChild(img); }) }
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>
|