防抖与节流
防抖
任务频繁触发的情况下,只有任务触发的间隔超过指定间隔的时候,任务才会执行。
方法实现
function debounce(fn, delay) { var timer; return function(args) { var _this = this; var _args = args; clearTimeout(timer); timer = setTimeout(function() { fn.apply(_this, _args); }, delay) } } // 箭头函数 function debounce(fn, delay) { let timer; return (...args)=>{ clearTimeout(timer) timer = setTimeout(()=>{ fn(...args) }, delay) } }
节流
指定时间间隔内只会执行一次任务;
- 方法实现
function throttle(fn, threshhold) {
var timer;
var lastTime = new Date();
return function(args) {~~~~
var _this = this;
var _args = args;
var now = new Date();
clearTimeout(timer)
if (now - lastTime >= threshhold) {
fn.apply(_this, _args);
lastTime = now;
} else {
timer = setTimeout(function() {
fn.apply(_this, _args);
}, threshhold)
}
}
}
//箭头函数
function throttle(fn, delay) {
let timer;
let threshTime = new Date();;
return (...args) => {
let now = new Date();
clearTimeout(timer);
if(threshTime && now - threshTime > delay) {
threshTime = now;
fn(...args);
} else {
timer = setTimeout(()=>{
fn(...args)
}, delay);
}
}
}