# 防抖动和节流阀
2 min read
Table of Contents
防抖动就是延迟执行函数,在延迟期间,若执行函数被重新调用,则重新计算延迟时间。
节流阀就是执行函数在规定时间内只允许执行一次。
防抖动(debounce)
// 模拟简单的debounceconst debounce = function (func, wait) { let timerId = null if (typeof func !== 'function') { throw new TypeError('Expected a function') } wait = +wait || 0 return function () { if (timerId !== null) clearTimeout(timerId) timerId = setTimeout(func, wait) }}节流阀(throttle)
// 模拟简单的throttleconst throttle = function (func, wait) { var lastInvokeTime = 0 return function () { var time = Date.now() if (time - lastInvokeTime > wait) { func() lastInvokeTime = time } }}应用场景
- 防抖动
- 搜索联想,在不断的输入的时候,使用防抖减少请求。
- window 在触发 resize 的时候,使用防抖减少渲染计算。
- 按钮点击,防止用户连击,防止发送多次请求。
- 节流阀
- 滚动加载,滚动底部的监听
- 高频点击,重复提交表单