File tree Expand file tree Collapse file tree 2 files changed +84
-0
lines changed
Expand file tree Collapse file tree 2 files changed +84
-0
lines changed Original file line number Diff line number Diff line change 1+ <!DOCTYPE html>
2+ < html lang ="en ">
3+ < head >
4+ < meta charset ="UTF-8 " />
5+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 " />
6+ < title > 图片懒加载</ title >
7+ </ head >
8+ < body >
9+ < script src ="./index.js "> </ script >
10+ </ body >
11+ </ html >
Original file line number Diff line number Diff line change 1+ function limitLoad ( urls , handlers , limit ) {
2+ const sequence = [ ] . concat ( urls ) ; //拷贝另一个数组
3+ let promises = [ ] ;
4+ promises = sequence . splice ( 0 , limit ) . map ( ( url , index ) => {
5+ return handlers ( url ) . then ( ( ) => {
6+ return index ;
7+ } ) ;
8+ } ) ;
9+ let p = Promise . race ( promises ) ;
10+ for ( let i = 0 ; i < sequence . length ; i ++ ) {
11+ p = p . then ( ( res ) => {
12+ promises [ res ] = handlers ( sequence [ i ] ) . then ( ( ) => {
13+ return res ;
14+ } ) ;
15+ return Promise . race ( promises ) ;
16+ } ) ;
17+ }
18+ //链式调用
19+ }
20+ const urls = [
21+ {
22+ time : 1000 ,
23+ info : "link1" ,
24+ } ,
25+ {
26+ time : 1000 ,
27+ info : "link2" ,
28+ } ,
29+ {
30+ time : 1000 ,
31+ info : "link3" ,
32+ } ,
33+ {
34+ time : 1000 ,
35+ info : "link4" ,
36+ } ,
37+ {
38+ time : 1000 ,
39+ info : "link5" ,
40+ } ,
41+ {
42+ time : 1000 ,
43+ info : "link6" ,
44+ } ,
45+ {
46+ time : 1000 ,
47+ info : "link7" ,
48+ } ,
49+ {
50+ time : 1000 ,
51+ info : "link8" ,
52+ } ,
53+ {
54+ time : 1000 ,
55+ info : "link9" ,
56+ } ,
57+ {
58+ time : 1000 ,
59+ info : "link10" ,
60+ } ,
61+ ] ;
62+ function loadImg ( url ) {
63+ return new Promise ( ( resolve , reject ) => {
64+ console . log ( "----" + url . info + "start!" ) ;
65+ setTimeout ( ( ) => {
66+ console . log ( url . info + "ok!" ) ;
67+ resolve ( ) ;
68+ } , url . time ) ;
69+ } ) ;
70+ }
71+ limitLoad ( urls , loadImg , 3 ) ;
72+ //目的:为了实现限制同时加载的只有3个图片,如果一个加载完成,则立即引入下一个
73+ //不能.all 原因:是等3个同时加载完成,不是某一个加载完成并填补空缺
You can’t perform that action at this time.
0 commit comments