节流(滚动,隔⼀段时间只触发⼀次 第⼀个⼈说了算 在时间结束出发)
// func是⽤户传⼊需要防抖的函数
// wait
是等待时间
const
throttle
=
(
func
,
wait
=
50
)
=>
{
//
上⼀次执⾏该函数的时间
let
lastTime
=
0
return
(
...
args
)
=>
{
//
当前时间
let
now
= +
new
Date
()
//
将当前时间和上⼀次执⾏函数时间对⽐
//
如果差值⼤于设置的等待时间就执⾏函数
if
(
now
-
lastTime
>
wait
) {
lastTime
=
now
func
.
apply
(
this
,
args
)
}
}
}
setInterval
(
throttle
(()
=>
{
console
.
log
(
1
)
},
500
),
1
)
防抖(输⼊,完成后再统⼀发送请求,最后⼀个⼈说了算 只认最后⼀次)
// func
是⽤户传⼊需要防抖的函数
// wait
是等待时间
const
debounce
=
(
func
,
wait
=
50
)
=>
{
//
缓存⼀个定时器
id
let
timer
=
0
//
这⾥返回的函数是每次⽤户实际调⽤的防抖函数
//
如果已经设定过定时器了就清空上⼀次的定时器
//
开始⼀个新的定时器,延迟执⾏⽤户传⼊的⽅法
return function
(
...
args
) {
if
(
timer
)
clearTimeout
(
timer
)
timer
=
setTimeout
(()
=>
{
func
.
apply
(
this
,
args
)
},
wait
)
}
}