debounce限制多长时间才能执行一次,throttle限制多长时间必须执行一次,一个限制上限、一个限制下限
防抖
适用范围 input框实时搜索 防抖
function debounce(func, delay) {
let timeout = null;.//闭包
return function(e) {
if(timeout){
clearTimeout(timeout)
}
var context = this, args = arguments
timeout = setTimeout(function(){
func.apply(context, args);
},delay)
};
};
@@@@ = debounce(fn, 380);
节流
适用范围在 比input, keyup更频繁触发的事件中,如resize, touchmove, mousemove, scroll。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);
}
}
}
var mousemove = throttle(function(e) {
console.log(e.pageX, e.pageY)
});
// 绑定监听
document.querySelector("#panel").addEventListener('mousemove', mousemove);
throttle(fn,delay){
let valid = true
return function() {
if(!valid){
return false
}
var context = this, args = arguments
valid = false
setTimeout(() => {
fn.apply(context, args)
valid = true;
}, delay)
}
}