# 什么是节流,防抖

节流 就是用户重复点击,不断的发出请求,或滚动条不断滚动,触发的事件会占用很大的一部分内存,所以就出现了节流
防抖 就是搜索的时候,我们每搜一个关键字后就会马上请求接口,其实这是不需要的,为解决这一问题就出现的防抖,指超出指定时间后才会执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//节流1
function throttel(name="随便起",time=2000,msg="点击的速度太快了"){
return new Promise((resolve,reject)=>{
if(this[name]){
console.log(`${msg}`)
return false;
}
this[name]=true;
setTimeout(()=>{
this[name]=false;
},time);
resolve()
})
}
//使用
button.onclick=()=>{
throttel(`随便起`).then(()=>{
console.log('这里写事件')
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//节流2
function throttle(fun, delay = 1000) {
let last, deferTimer;
return function (args) {
let that = this;
let _args = arguments;
let now = +new Date();
if (last && now < last + delay) {
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fun.apply(that, _args);
}, delay)
} else {
last = now;
fun.apply(that, _args);
}
}
}

function fn(){
console.log(111);
}
button.onclick=throttle(fn,2000)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//防抖
function debounce(fun, delay = 200) {
return function (args) {
//获取函数的作用域和变量
let that = this
let _args = args
//每次事件被触发,都会清除当前的timeer,然后重写设置超时调用
clearTimeout(fun.id)
fun.id = setTimeout(function () {
fun.call(that, _args)
}, delay)
}
}

function fn(){
console.log(111);
}
button.onclick=debounce(fn,2000)
更新于

请我喝[茶]~( ̄▽ ̄)~*

高祥 微信支付

微信支付

高祥 支付宝

支付宝

高祥 贝宝

贝宝