直接上代码
防抖(js)
export function debounce(fn, time, immediate) {let timer = null;const debounced = function () {const context = this;const args = arguments;if (timer) clearTimeout(timer); if (immediate) {const callNow = !timer;timer = setTimeout(() => {timer = null;}, time || 500);if (callNow) fn.apply(context, args);} else {timer = setTimeout(function () {fn.apply(context, args);}, time || 500);}};debounced.cancel = function () {clearTimeout(timer);timer = null;};return debounced;
}
节流(js)
function throttle(func, wait, immediate = true) {let prevTime = 0;let first = true;const execu = ({ currentTime, context, args }) => {if (currentTime >= prevTime) {func.apply(context, args);first = true;}};const reset = (currentTime) => {if (first) {prevTime = currentTime + wait;first = false;}}return function () {const context = this;const args = arguments;const currentTime = Date.now();if (immediate) {execu({ currentTime, context, args });reset(currentTime);} else {reset(currentTime);execu({ currentTime, context, args });}}
}