javascript中的防抖与节流

防抖与节流是在实际开发中使用较多的功能,虽然平时咱们可使用lodash提供的功能方法,可是为了知其因此然,咱们仍是须要了解下它的实现原理。网络

1. 防抖 (debounce)

做用:防抖顾名思义就是防止抖动,如比一个常见的使用场景,当咱们填完用户名密码后须要点击登陆按钮,若是个人手抖动了一下,按了两次登陆按钮,是否是就会请求两次登陆接口呢,因此为了节约网络资源,防止没必要要的网络开销,防抖是必不可少的。(咱们能够通俗的记忆: 防抖是为了防止手抖,触发屡次事件,它的目的是让事件在指定时间只触发一次)。this

分类:即时触发和延时触发spa

即时触发:第一次点击时候即执行事件,后面每次点击都会刷新下次再生效的时间。code

延时触发:每次点击都会刷新下次生效的时间,当到时间后就会触发一次事件。blog

经过文字说可能理解有点困难,下面咱们仍是上代码。接口

即时触发

function debounce(fn, wait) {
    let timer = null;
   let context = null;
return function () {
context = this;
!timer && fn(context, ...arguments); if (timer) { clearTimeout(timer); timer = null; } timer = setTimeout(() => { clearTimeout(timer); timer = null; }, wait); } }

延时触发

function delayDebounce(fn, wait) {
    let timer = null;
   let context = null;
return function() {
     context = this;
if(timer) { clearTimeout(timer); timer = null; } timer = setTimeout(() => { fn(context, ...arguments); clearTimeout(timer); timer = null; }, wait); } }

下面咱们将这两个方法合并下,添加参数进行区别。事件

function debounce(fn, wait, immediate = true) {
    let timer = null;
    let context = null;

    return function () {
        context = this;

        if (immediate) {
            !timer && fn.call(context, ...arguments);
        }

        if (timer) {
            clearTimeout(timer);
            timer = null;
        }

        timer = setTimeout(() => {
            !immediate && fn(context, ...arguments)

            clearTimeout(timer);
            timer = null;
        }, wait);
    }
}

 

2. 节流

做用:顾名思义,节流就是节约流动。咱们常常见到的一个使用场景就是春节期间各大公司开发的抢红包功能,须要咱们不停的点击按钮,为了减小网络请求,咱们就能够减小请求次数,让网络请求减小,一样达到减小网络开销的问题。(对比防抖,咱们能够这样记忆:节流是减小网络请求次数,可是实际仍是触发屡次)。资源

节流也分为即时执行版本和延时执行版本。开发

即时执行

function throttling(fn, wait) {
    let timer = null;
    let context = this;

    return function () {
        !timer && fn.call(context, ...arguments);

        if (!timer) {
            timer = setTimeout(() => {
                clearTimeout(timer);
                timer = null;
            }, wait);
        }
    }
}

延时执行

function throttling(fn, wait, immediate = true) {
    let timer = null;
    let context = this;

    return function () {
        if (immediate) {
            !timer && fn.call(context, ...arguments);
        }

        if (!timer) {
            timer = setTimeout(() => {
                !immediate && fn.call(context, ...arguments);
                clearTimeout(timer);
                timer = null;
            }, wait);
        }
    }
}

 

浅陋见识,不足之处,请大神指正。it

相关文章
相关标签/搜索