0
点赞
收藏
分享

微信扫一扫

前端面试准备--手写代码--防抖和节流

kiliwalk 2022-03-12 阅读 75

1、防抖(debounce)

  • 目的:避免用户多次触发事件,导致事件处理程序响应过快而产生抖动感。
  • 实现方法:触发事件时,利用定时器让事件处理程序在一段时间后执行。与此同时,在事件处理程序前若再次触发事件,则取消前一次的定时任务。
  • 实现代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text">
</body>
<script>
    // output是业务处理函数
    function output() {
        console.log(this.value);
    }
    // 这里的具体应用场景是防止用户输入文本框时,触发keyup事件过快而多次执行output函数
    function decounce(fn, delay) {
        let timer;
        return function (...args) {
            // 如果有定时器,取消定时器任务
            if (timer) {
                clearInterval(timer)
            }
            // 每次触发事件都会生成定时器,在一段时间后调用事件处理程序
            timer = setTimeout(() => {
                fn.apply(this, args)

            }, delay)
        }
    }
    const inp = document.querySelector('input');
    // 绑定事件
    inp.addEventListener('keyup', decounce(output, 500));
</script>

</html>

2、节流(throttle)

  • 目的与节流差不多。
  • 与防抖区别:防抖是只执行最后一次触发的事件,而节流是控制执行次数。
  • 代码实现
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            height: 2000px;
        }
    </style>
</head>

<body>

</body>
<script>
    function throttle(func, wait) {
        let timer = null;
        return function () {
            if (!timeout) {
                // 这个判断的意思就是如果当前没有定时器任务则可以让用户触发事件生成定时器任务
                timer = setTimeout(() => {
                    // 只有当当前定时器任务执行完,将timeout设置为null时,用户触发的事件才会再一次生成定时器任务
                    timer = null;
                    func.apply(this, arguments)
                }, wait)
            }

        }
    }
    /*正常事件监听*/
    document.addEventListener('mousemove', throttle(function (e) {
        console.log(e.offsetX);
    }, 500))
</script>

</html>
举报

相关推荐

0 条评论