前端知识点复习-防抖和节流
防抖:一段时间内触发很多次的事件,限制到只执行一次,即只有最后一次触发事件生效,如页面滚动事件,代码:
function debounce(func, wait) { let timer = null; //闭包 return () => { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { debounce(func, wait) }, wait) } }
节流:事件触发后,过一段时间才能重新触发,代码:
function throttle(func, wait) { let complete = true; //闭包 return () => { if (!complete) { return; } complete = false; setTimeout(() => { func(); complete = true; }, wait); } }