节流和防抖

88 阅读1分钟

防抖

防抖,即短时间内大量触发同一事件,只会执行一次函数,实现原理为设置一个定时器,约定在xx毫秒后再触发事件处理,每次触发事件都会重新设置计时器,直到xx毫秒内无第二次操作。

const debounce = (func, wait) => {
            let timeout = null;
            return function () {
                let context = this;

                let args = arguments;

                if (timeout) clearTimeout(timeout)

                timeout = setTimeout(() => {
                    func.apply(context, args)
                }, wait)
            }
        }

节流

节流,是间隔执行,函数节流即每隔一段时间就执行一次,实现原理为设置一个定时器,约定xx毫秒后执行事件,如果时间到了,那么执行函数并重置定时器。

方案一:
const throttle = (func, wait) => {
            let timeout = null;
            return function () {
                let context = this;
                let args = arguments;

                if (!timeout) {
                    timeout = setTimeout(() => {
                        timeout = null;
                        func.apply(context, args)
                    }, wait)
                }
            }
        }

方案二:
        const throttle2 = (func, wait) => {
            let prev = 0;

            return function () {
                let now = Date.now();

                let context = this;

                let args = arguments;

                if (now - prev > wait) {
                    func.apply(context, args)
                    prev = now;
                }
            }
        }