fdf78b6f5e11

为什么要使用这两种策略

在我们日常的开发中,以下几种情况会高频率的触发事件:

resize

scroll

click

mousemove

keydown

高频率的触发事件,会过度损耗页面性能,导致页面卡顿,页面抖动,尤其是当这些事件回调函数中包含ajax等异步操作的时候,多次触发会导致返回的内容结果顺序不一致,而导致得到的结果非最后一次触发事件对应的结果。

两种策略的工作方式

Debounce:一部电梯停在某一个楼层,当有一个人进来后,20秒后自动关门,这20秒的等待期间,又一个人按了电梯进来,这20秒又重新计算,直到电梯关门那一刻才算是响应了事件。

Throttle:好比一台自动的饮料机,按拿铁按钮,在出饮料的过程中,不管按多少这个按钮,都不会连续出饮料,中间按钮的响应会被忽略,必须要等这一杯的容量全部出完之后,再按拿铁按钮才会出下一杯。

使用方式

这里我们使用 Lodash 库里面实现的debouce和throttle方法。

lodash支持自定义封装,使用下面两个命令封装一个我们自己的lodash库。

$ npm i -g lodash-cli

$ lodash include=debouce,throttle

debounce调用方法:_.debounce(func, [wait=0], [options={}]) 返回一个具有debounce策略的新函数。

throttle调用方法:_.throttle(func, [wait=0], [options={}]) 返回一个具有throttle策略的新函数。

debounce参数列表

func (Function): The function to debounce.

[wait=0] (number): The number of milliseconds to delay.

[options={}] (Object): The options object.

[options.leading=false] (boolean): Specify invoking on the leading edge of the timeout.

[options.maxWait] (number): The maximum time func is allowed to be delayed before it's invoked.

[options.trailing=true] (boolean): Specify invoking on the trailing edge of the timeout.

下面的例子是在移动端使用 rem 布局常用的一个函数,侦听resize事件改变根元素的fontSize,这种情况下适用debounce策略:

;(function (win, doc) {

let docEl = doc.documentElement;

const psdWidth = 750,

psdHeight = 1200,

aspect = psdWidth / psdHeight;

const recalc = function() {

const clientWidth = docEl.clientWidth;

const clientHeight = docEl.clientHeight;

if (!clientWidth) return;

if((clientWidth / clientHeight) > aspect) {

let ratio = clientWidth / psdWidth;

docEl.style.fontSize = 100 * ratio + 'px';

} else {

let ratio = clientHeight / psdHeight;

docEl.style.fontSize = 100 * ratio + 'px';

}

};

if (!doc.addEventListener) return;

const debounceRecalc = _.debounce(recalc, 200, {});

win.addEventListener('resize', debounceRecalc, false);

win.addEventListener('orientationchange', debounceRecalc, false);

debounceRecalc();

})(window, document)

这个例子中,使用throttle策略,点击一次生成一行文字,1s中无论怎么点击,都只生成一行文字:

;(function(){

let throttleBtn = document.querySelector('.throttle-click');

let text = document.querySelector('.show-text');

let clickHandler = _.throttle(function (){

text.innerHTML += '

do it.

';

console.log('do it.')

}, 1000, {});

throttleBtn.addEventListener('click', clickHandler);

})();

完整demo地址:demo

实现源代码

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐