let throttle = function(func, delay) { let timer = null; return ()=> { if (!timer) { timer = setTimeout(function() { func.apply(this, arguments); timer = null; }, delay); } }; }; function handle() { console.log(Math.random()); } window.addEventListener("scroll", throttle(handle, 1000)); //事件处理函数
防抖
function debounce(fn, wait) { var timeout = null; return function() { if (timeout !== null) clearTimeout(timeout);//如果多次触发将上次记录延迟清除掉 timeout = setTimeout(()=> { fn.apply(this, arguments); timeout = null; }, wait); }; } // 处理函数 function handle() { console.log(Math.random()); } // 滚动事件 window.addEventListener("scroll", debounce(handle, 1000));
浙公网安备 33010602011771号