函数节流.html
1.46 KB
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
<!DOCTYPE>
<HTML>
<head>
<title>函数节流</title>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no" />
<style>
*{
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div style="background: pink;height: 100vh;">函数节流:指定时间间隔内只会执行一次任务</div>
<div style="background: orange;height: 100vh;" id="text"></div>
<script>
//方法一:Date
function throttle_01(fn,timeout = 300){
let old = new Date().getTime();
return function(){
let now = new Date().getTime();
if(now - old < timeout){
return
}
old = now;
fn()
}
}
//方法二:定时器:set
function throttle(fn,timeout = 300){
let canRun = true
let fn1 = fn();
return function(){
if(!canRun){
return
}
setTimeout(() => {
fn1();
canRun = true
}, timeout);
canRun = false;
}
}
let count = 0;
function handle (){
document.getElementById('text').innerHTML = count++
}
window.addEventListener('scroll',throttle(handle))
</script>
</body>
</HTML>