防抖
包括要不要点击后立即执行,还是要一段时间后执行
function debounce(func, wait, immediate) {
let timeOut, result;
let debounced = function () {
//立即执行
let context = this;
let args = arguments;
if (timeOut) clearTimeout(timeOut);
if (immediate) {
let callNow = !timeOut;
timeOut = setTimeout(function () {
timeOut = null;
}, wait);
if (callNow) result = func.apply(context, args);
}
//不会立即执行
else {
timeOut = setTimeout(function () {
//绑定dom节点
result = func.apply(context, args);
timeOut = null;
}, wait);
}
return result;
};
debounced.cancel = function () {
clearTimeout(timeOut);
timeout = null;
};
return debounced;
}
节流
//包括第一次会执行,最后一次也会执行
function throttle(func, wait, options) {
let timeOut;
let old = 0;
if (!options) options = {
};
return function () {
let context = this;
let args = arguments;
let now = new Date.valueOf();
if (options.leading === false && !old) {
old = now;
}
if (now - old > wait) {
if (timeOut) {
//第一次会直接执行
clearTimeout(timeOut);
timeOut = null;
}
func.apply(context, args);
old = now;
} else if (!timeOut && options.trailing !== false) {
//最后一次也会被执行
timeOut = setTimeout(function () {
func.apply(context, args);
timeOut = null;
}, wait);
}
};
}