首页

  • 首页
  • 友链
  • 标签
  • 关于

函数节流和防抖封装

白羊座的梦 发布于 2020-03-01

函数节流和防抖封装

封装节流函数

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
	/*
函数节流:
一个频繁触发的函数 在规定的时间内
只让第一次函数执行有效
之后的函数执行都不生效

*/

var age = 29;
let name = "豪华"
function throttle (fn,delay){ //fn是需要降低执行频率的函数
let start = 0 //默认值
return function(...args){ //this-->document
let now = new Date()
if(now-start>=delay){ //如果两次时间差大于规定时间 才执行函数
fn.call(this,...args) //使this指向调用他的函数;
start = now//更新起始时间
}
}
}


let xxx = throttle(function(e){ //e 是xxx函数的
console.log(this,arguments,age,name);
},1000)

document.addEventListener('click',xxx)

封装防抖函数

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
	/*
函数防抖:
一个频繁触发的函数 在规定的时间内
只让最后一次函数执行生效
之前的函数执行的都不生效

*/

//函数防抖
function debounce(func,delay){
let timer = null;
return function(...args){//使用闭包
if(timer) clearTimeout(timer);
timer = setTimeout(()=>{
func.apply(this,args);//这个主要使用来传参的
},delay)
// timer = setTimeout(func,delay)//不需要传参就用这个
}
}

//使用防抖
const refresh = debounce(function(e){
console.log(this,e);
},50);
document.addEventListener('click',refresh);


function debounce(fn,delay){
let timer = null
return function(...args){ //this --> document
clearTimeout(timer)
timer = setTimeout(fn.bind(this,...args),delay) //...args是展开
}
}

let xxx = debounce(function(e){ //e 是xxx函数的
console.log(this,)
},2000)

document.addEventListener('click',xxx)
  • #方法
Newer
封装一些数组的方法
Older
“node路由模块化”

© 2020 白羊座的梦

Powered by Hexo Theme - flex-block