JS 防抖 实现

99 篇文章 12 订阅
33 篇文章 1 订阅

在前端开发中会遇到一些频繁的事件触发,比如:

  1. window 的 resize、scroll
  2. mousedown、mousemove
  3. keyup、keydown
<!DOCTYPE html>
<html lang="zh-cmn-Hans">

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1">
    <title>debounce</title>
    <style>
        #container{
            width: 100%; height: 200px; line-height: 200px; text-align: center; color: #fff; background-color: #444; font-size: 30px;
        }
    </style>
</head>

<body>
<div id="container"></div>
<script>
    var count = 1;
    var container = document.getElementById('container');

    function getUserAction() {
        container.innerHTML = count++;
    };

    container.onmousemove = getUserAction;
</script>
</body>

</html>

防抖的原理就是:你尽管触发事件,但是我一定在事件触发 n 秒后才执行,如果你在一个事件触发的 n 秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行,总之,就是要等你触发完事件 n 秒内不再触发事件,我才执行,真是任性呐!

第一版

移动完 1000ms 内不再触发,才执行事件

<script>
    function debounce(func, wait) {
        var timeout;
        return function () {
            clearTimeout(timeout)
            timeout = setTimeout(func, wait);
        }
    }

    var count = 1;
    var container = document.getElementById('container');

    function getUserAction() {
        container.innerHTML = count++;
    };


    container.onmousemove = debounce(getUserAction, 1000);

</script>

存在问题:在 getUserAction 函数中 console.log(this),在不使用 debounce 函数的时候,this 的值为:

<div id="container"></div>

但是如果使用我们的 debounce 函数,this 就会指向 Window 对象!

第二版

更正this的指向问题

<script>
    function debounce (func, wait) {
        var timeout

        return function () {
            var context = this

            clearTimeout(timeout)
            timeout = setTimeout(function () {
                func.apply(context)
            }, wait)
        }
    }

    var count = 1
    var container = document.getElementById('container')

    function getUserAction () {
        container.innerHTML = count++
    }

    container.onmousemove = debounce(getUserAction, 1000)
</script>

第三版:

event 对象问题

JavaScript 在事件处理函数中会提供事件对象 event,我们修改下 getUserAction 函数:

function getUserAction(e) {
    console.log(e);
    container.innerHTML = count++;
};

如果我们不使用 debouce 函数,这里会打印 MouseEvent 对象,

但是在我们实现的 debounce 函数中,却只会打印 undefined!

所以我们再修改一下代码:

function debounce(func, wait) {
    var timeout;
    return function () {
        var context = this;
        var args = arguments;
        clearTimeout(timeout)
        timeout = setTimeout(function(){
            func.apply(context, args)
        }, wait);
    }
}

第四版

不希望非要等到事件停止触发后才执行,我希望立刻执行函数,然后等到停止触发 n 秒后,才可以重新触发执行。

// 第四版
function debounce(func, wait, immediate) {
    var timeout;
    return function () {
        var context = this;
        var args = arguments;
        if (timeout) clearTimeout(timeout);
        if (immediate) {
            // 如果已经执行过,不再执行
            var callNow = !timeout;
            timeout = setTimeout(function(){
                timeout = null;
            }, wait)
            if (callNow) func.apply(context, args)
        }
        else {
            timeout = setTimeout(function(){
                func.apply(context, args)
            }, wait);
        }
    }
}

第五版

getUserAction 函数可能是有返回值的,所以我们也要返回函数的执行结果,但是当 immediate 为 false 的时候,因为使用了 setTimeout ,我们将 func.apply(context, args) 的返回值赋给变量,最后再 return 的时候,值将会一直是 undefined,所以我们只在 immediate 为 true 的时候返回函数的执行结果。

// 第五版
function debounce(func, wait, immediate) {
    var timeout, result;
    return function () {
        var context = this;
        var args = arguments;
        if (timeout) clearTimeout(timeout);
        if (immediate) {
            // 如果已经执行过,不再执行
            var callNow = !timeout;
            timeout = setTimeout(function(){
                timeout = null;
            }, wait)
            if (callNow) result = func.apply(context, args)
        }
        else {
            timeout = setTimeout(function(){
                func.apply(context, args)
            }, wait);
        }
        return result;
    }
}

第六版

希望能取消 debounce 函数,比如说我 debounce 的时间间隔是 10 秒钟,immediate 为 true,这样的话,我只有等 10 秒后才能重新触发事件,现在我希望有一个按钮,点击后,取消防抖,这样我再去触发,就可以又立刻执行

<script>
    // 第六版
    function debounce(func, wait, immediate) {

        var timeout, result;

        var debounced = function () {
            var context = this;
            var args = arguments;

            if (timeout) clearTimeout(timeout);
            if (immediate) {
                // 如果已经执行过,不再执行
                var callNow = !timeout;
                timeout = setTimeout(function(){
                    timeout = null;
                }, wait)
                if (callNow) result = func.apply(context, args)
            }
            else {
                timeout = setTimeout(function(){
                    func.apply(context, args)
                }, wait);
            }
            return result;
        };

        debounced.cancel = function() {
            clearTimeout(timeout);
            timeout = null;
        };

        return debounced;
    }



    var count = 1;
    var container = document.getElementById('container');

    function getUserAction(e) {
        container.innerHTML = count++;
    };

    var setUseAction = debounce(getUserAction, 10000, true);

    container.onmousemove = setUseAction;

    document.getElementById("button").addEventListener('click', function(){
        setUseAction.cancel();
    })
</script>

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现JS防抖的代码,可以参考以下步骤: 1. 创建一个防抖函数,命名为`debounce`,该函数接收两个参数:要执行的函数`func`和延迟时间`delay`。 2. 在`debounce`函数内部创建一个变量`timer`用来保存定时器的ID。 3. 返回一个函数,命名为`debounced`,该函数用于实际执行防抖操作。 4. 在`debounced`函数内部,使用`clearTimeout`来清除之前的定时器。 5. 创建一个新的定时器,将其ID保存到`timer`变量。 6. 在新的定时器,使用`setTimeout`来延迟执行传入的函数`func`,延迟时间为`delay`。 7. 最后,将`debounced`函数作为返回值返回。 下面是具体的代码实现: ```javascript function debounce(func, delay) { let timer; return function debounced() { clearTimeout(timer); timer = setTimeout(() => { func(); timer = null; }, delay); }; } ``` 这样,你就可以使用`debounce`函数来创建一个防抖函数了。可以将要执行的函数和延迟时间作为参数传入,然后将返回的函数绑定到相应的事件上。 例如,使用`debounce`函数创建一个防抖函数,并将其绑定到输入框的`input`事件上: ```javascript const debouncedFunction = debounce(() => { console.log('执行防抖操作'); }, 1000); Input.oninput = debouncedFunction; ``` 这样,在输入框输入内容时,只有在停止输入后的1秒内才会执行防抖函数的代码。 如果需要在某些情况下取消防抖操作,可以调用返回的函数的`cancel`方法来清除定时器。例如,点击一个按钮来取消防抖操作: ```javascript btn.onclick = function() { debouncedFunction.cancel(); }; ``` 这样,点击按钮时就会取消之前设置的防抖操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [js防抖功能实现](https://blog.csdn.net/weixin_59554510/article/details/126670272)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wflynn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值