防抖节流
触发高频事件后 n 秒内函数只会执行一次,如果 n 秒内高频事件再次被触发,则重新计算时间。(防抖让一个函数在一定间隔内没有被调用时,才开始执行被调用方法)
export const Debounce = (function () { let timer = null return function (callback, ms) { clearTimeout(timer) timer = setTimeout(callback, ms) } })() 或者 let timer = null; export const Debounce = function (fn, delay) { console.log("进入Debounce") return function () { let self = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { fn.apply(self, args); }, delay); }; };
节流是让一个函数无法在很短的时间间隔内连续调用,当上一次函数执行后过了规定的时间间隔,才能进行下一次该函数的调用。
function throttle(fn,delay){ let timer = null; return function(){ if(!timer){ timer = setTimeout(function(){ fn(); timer = null; },delay) } } } function handle(){ console.log(Math.random()); } window.addEventListener("mousemove",throttle(handle,1000));