防抖
function debounce(fn, delay = 666, immediate = false, callBack) {
let timer,
isInvoke = true;
function _debounce(...args) {
if (immediate && isInvoke) {
const result = fn.apply(this, args);
isInvoke = false;
if (callBack) callBack(result);
} else {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
const result = fn.apply(this, args);
if (!isInvoke) isInvoke = true;
if (callBack) callBack(result);
}, delay);
}
}
_debounce.cancel = function () {
if (timer) clearTimeout(timer);
};
return _debounce;
}
<input type="text" />
const inpt = document.querySelector('input');
inpt.addEventListener(
'input',
debounce(getSource, 1000, true, res => {
console.log(res);
})
);
function getSource(e) {
console.log('发了请求', this, e);
return '请求返回值';
}
节流
function throttle(fn, delay = 666, immediate = false, callBack) {
let timer = null, isInvoke = true;
function _throttle(...args) {
if (immediate && isInvoke) {
const result = fn.apply(this, args);
isInvoke = false;
if (callBack) callBack(result)
} else {
if (timer) return;
timer = setTimeout(() => {
const result = fn.apply(this, args);
if (callBack) callBack(result)
timer = null;
}, delay);
}
}
_throttle.cancel = function () {
if (timer) clearTimeout(timer)
}
return _throttle;
}
<input type="text" />
const inpt = document.querySelector('input');
inpt.addEventListener(
'input',
throttle(getSource, 666, true, res => {
console.log(res);
})
);
function getSource(e) {
console.log('发了请求', this, e);
return '请求返回值';
}
console.log(throttle().cancel);