android 点击频率控制_控制事件触发频率的两种策略:Debounce && Throttle

本文介绍了在Android开发中控制事件触发频率的两种策略:Debounce和Throttle,以减少高性能损耗和页面卡顿。Debounce策略如电梯自动关门,Throttle策略如饮料机出饮料。通过Lodash库实现这两个功能,并提供了具体的代码示例,适用于resize事件处理和按钮点击事件控制。
摘要由CSDN通过智能技术生成

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

实现源代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值