1.防抖函数:
debounce中文是“去弹跳”,它的概念是从机械开关和继电器中的去弹跳衍生出来的,就是将多个信号合并成一个信号。当事件被多次触发时,只执行最后一次。
function debounce(func, delay) {
var timeout;
return function(e) {
console.log("清除",timeout,e.target.value)
clearTimeout(timeout);
var context = this, args = arguments
console.log("新的",timeout, e.target.value)
timeout = setTimeout(function(){
console.log("----")
func.apply(context, args);
},delay)
};
};
应用场景:输入框搜索 提交按钮点击事件
2.节流函数
throttle中文意思是节流阀,字面意思是它是让水流的速度整体放慢,不是让它不能流动。它的作用是让函数在某个时间段只执行一次。
function throttle(fn, threshhold) {
var timeout
var start = new Date;
var threshhold = threshhold || 160
return function () {
var context = this, args = arguments, curr = new Date() - 0
clearTimeout(timeout)//总是干掉事件回调
if(curr - start >= threshhold){
console.log("now", curr, curr - start)//注意这里相减的结果,都差不多是160左右
fn.apply(context, args) //只执行一部分方法,这些方法是在某个时间段内执行一次
start = curr
}else{
//让方法在脱离事件后也能执行一次
timeout = setTimeout(function(){
fn.apply(context, args)
}, threshhold);
}
}
}
节流函数适用于更加频繁的触发的情况,比如resize、touchmove、mousemove、scroll等频繁触发的事件,它会强制函数以固定的频率进行,适用于动画场景。
模拟场景:
http://demo.nimius.net/debounce_throttle/
在节流函数中,异步函数的作用是延迟时间,并让方法在脱离事件之后执行最后一次。
3.调用方法
const a = throttle(() => { console.log(123) }, 3500)
a()
a()
版权声明:本文为weixin_38208314原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。