防抖(debounce) and 节流(throttle)
1. 防抖:简单来说即当一个事件我们不希望其频繁被触发,可以使用防抖. 原理是当一个事件被触发后,如果在未被执行前【处于setTimeout的delay阶段】再次触发该事件,则事件重新计时.
function debounce(func, delay) { let timer = undefined; return function () { let context = this; let args = arguments; if (timer) { clearTimeout(timer); // 清除计时器后timer的值是什么?[思考] } timer = setTimeout(() => { func.apply(context, args); }, delay) } }
2. 节流:如果一个事件触发后,在未执行前再次触发该事件,那么此操作无效,直到第一次触发事件完成之后的触发才能生效.
function throttle(func, delay) { let timer = null; return function () { let context = this; let args = arguments; if (!timer) { timer = setTimeout(() => { func.apply(context, args); timer = null; }, delay) } } }

浙公网安备 33010602011771号