-
Notifications
You must be signed in to change notification settings - Fork 2
/
lazyLoading.html
88 lines (78 loc) · 2.24 KB
/
lazyLoading.html
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>lazyLoading 懒加载</title>
</head>
<style type="text/css">
#box {
display: inline-block;
width: 200px;
height: 50px;
line-height: 50px;
border: 1px solid #ccc;
text-align: center;
cursor: pointer;
}
</style>
<body>
<div id="box">点击测试</div>
<script>
/**
* lazyLoading 懒加载
* options:
* data 需要进行懒加载的数据 Array
* cb 每次需要处理的回调
* endFn 所有数据处理完成后的回调
* rows 每次加载多少条
* step 每次处理时间间隔
*/
function lazyLoading(options) {
var data = options.data || [],
endFn = options.endFn,
cb = options.cb,
_index = 0,
len = data.length,
rows = options.rows || 10, //每次加载多少条
step = options.step || 500,
forLen = rows * _index,
arr = [];
var intervalId = setInterval(function () {
_index += 1
if (len - forLen > rows) {
forLen = rows * _index
} else if (len - forLen <= rows && len - forLen > 0) {
forLen = len
} else {
clearInterval(intervalId)
endFn && endFn()
return
}
for (var i = rows * (_index - 1); i < forLen; i++) {
arr.push(data[i])
}
cb && cb(arr)
arr = []
}, step)
}
let data = [];
for (let i = 0; i < 105; i++) {
data.push(i)
}
box.onclick = function () {
const options = {
data: data,
rows: 5,
step: 1000,
endFn: function () {
console.log('It is done!')
},
cb: function (data) {
console.log(data)
}
}
lazyLoading(options)
}
</script>
</body>
</html>