防抖 debounce 简单来说就是防止抖动
当持续触发事件时 debounce 会合并事件且不会去触发事件,当一定时间内没有触发在这个事件时,才真正去触发事件。
// 防抖,传入回调函数和设置响应时间
function debounce(fn,delay){
var delay=delay||200;
var timer;
return function(){
var th=this;
var args=arguments;
if (timer) {
clearTimeout(timer);
}
timer=setTimeout(function () {
timer=null;
fn.apply(th,args);
}, delay);
};
}
// 处理函数
function handle() {
console.log('输入你要的操作');
}
// 所以必须要滚动事件
window.addEventListener('scroll', debounce(handle, 1));
节流
这个throttle节流的功能就是在固定的间隔时间执行回调函数,最常用的用处就是resize,scroll事件中处理。
function Throttle(fn, t){
let last;
let timer;
let interval = t || 500;
return function () {
let args = arguments;
let now = +new Date();
if (last && now - last < interval) {
clearTimeout(timer);
timer = setTimeout(() => {
last = now;
fn.apply(this, args);
}, interval);
} else {
last = now;
fn.apply(this, args);
}
}
};
debounce用在keydown事件上验证用户名最好。而throttle用在resize改变布局上,onscroll滚动时候的。