- 防抖动(停止触发时间超过设定的等待时间,再触发,第一次需要立即触发)
function debounce(fn, delay, immediate) {
let timer = null;
return function() {
let context = this;
let args = arguments;
if(immediate) {
var callNow = !timer;
if(callNow) {
fn.apply(context, args);
}
}
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(context, args);
}, delay);
}
}
- 节流(长时间频繁触发,只在设定的时间点规律性的触发一次。并且保留最后一次的操作,第一次操作照样延迟触发)
function throttle(fn, wait, options) {
var previous = 0;
var later = function() {
fn.apply(this, arguments);
previous = options.leading === false ? 0 : Date.now();
}
return function() {
var now = Date.now();
let context = this;
let args = arguments;
if(!previous && options.leading === false) {
previous = now;
}
var remaining = wait - (now - previous);
if(remaining <= 0) {
if(timeout) {
clearTimeout(timeout);
timeout = null;
}
fn.apply(context, args);
previous = now;
} else if(!timeout && options.trailing){
timeout = setTimeout(later, remaining);
}
}
}