android timer后函数继续执行_JavaScript常用技巧之函数防抖

在触发一段时间后执行事件,如果这段时间内又触发了,则继续等待同样的时间。

防抖在实际开发中使用场景还是蛮多,比如列表的实时搜索等。延时执行,这很容易想到使用setTimeout来实现。

基础版

function debounce(func, wait) {    let timer;        return function () {        timer && clearTimeout(timer);        timer = setTimeout(func, wait);    };}

测试一下

// 使用input输入框做一个测试// html
9b8bc9f5816d5c97b78e9661c0734c9f.gif


嗯。好像没什么问题。不过我们发现上面在获取input的值的时候使用的是input.value,那其实oninput事件应该是存在一个参数是event,可以直接使用event.target.value获取。

// 使用input输入框做一个测试// html

不出意料的报错了,这是因为debounce函数返回的是一个新的函数,并没有将原有函数的this值绑定到新的函数上,也没有将参数传递给新的函数。我们来改一改。

处理了this和参数的版本

function debounce(func, wait) {    let timer;        return function (...args) {        timer && clearTimeout(timer);                timer = setTimeout(() => {            func.apply(this, args);        }, wait);    };}

这时候又来了个新需求,需要在计时开始时执行,而不是在结尾执行。同样的,原来的逻辑不变,只是需要新增一个立即执行的逻辑。想一想我们的需求:立即执行,然后在固定的一段时间内不再触发第二次 。在立即执行代码之后,可以设置一个变量flag(初始值为true)用来记录上一次执行的时间到现在是否超过wait,如果超过则将flag设置为true,意味着可以再次执行。

function debounce(func, wait, immediate) {    let timer;    return function (...args) {        timer && clearTimeout(timer);        if (immediate) {            // timer就是我们使用的flag            if (!timer) {                func.apply(this, args);            }                        // 在代码执行的wait s之后将timer设置为null            // 当下一次执行当前函数则可以触发判断 !timer === true            timer = setTimeout(() => {                timer = null;            }, wait);        } else {            timer = setTimeout(() => {                func.apply(this, args);            }, wait);        }    };}

当然,我们还可以像lodash一样,添加cancel、pending等方法。

function debounce(func, wait, immediate) {    let timer;        const debounced = function (...args) {        timer && clearTimeout(timer);            if (immediate) {            if (!timer) {                func.apply(this, args);            }                        timer = setTimeout(() => {                timer = null;            }, wait);        } else {            timer = setTimeout(() => {                func.apply(this, args);                timer = null;            }, wait);        }    };        debounced.cancel = function() {        timer && clearTimeout(timer);    }        debounced.pending = function() {        return !!timer;    }        return debounced;}

文章来源:https://segmentfault.com/newest

最后

刚整理 2020 年全套最新精品技术资料免费发给你! (原价最少8999元,超2000G!)

2bddcd422c919a570a53dbce996bc757.png
58201b063246ba00cc4637d5a11115e0.png

领取 看看下面!!

1、点赞 + 评论 (勾选 “转发” )

2、关注小编私信。点击头像,关注。并私信回复关键词: 1024

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值