防抖 节流 原理、区别以及应用,并用JavaScript进行实现

防抖(Debounce)原理:

在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时。(不停的触发事件,只执行最后一次 ===> 指的是某个函数在某段时间内,无论触发了多少次回调,都只执行最后一次。假如我们设置了一个等待时间 3 秒的函数,在这 3 秒内如果遇到函数调用请求就重新计时 3 秒,直至新的 3 秒内没有函数调用请求,此时执行函数,不然就以此类推重新计时。)

防抖应用场景:

  1. 输入框输入事件,只在用户停止输入一段时间后才执行搜索操作。
  2. 窗口大小变化事件,只在用户停止调整窗口大小一段时间后才执行相应操作。
  3. 防止多次提交按钮,只执行最后提交的一次

节流(Throttle)原理:

规定在一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。(函数节流指的是某个函数在一定时间间隔内(例如 3 秒)只执行一次,在这 3 秒内 无视后来产生的函数调用请求,也不会延长时间间隔。)

节流应用场景:

  1. 滚动事件,限制在滚动过程中只触发一次函数,减少触发次数。
  2. 鼠标移动事件,限制在一定时间内只执行一次函数,减少函数的执行频率。
  3. 拖拽场景:固定时间内只执行一次,防止超高频次触发位置变动
  4. 缩放场景:监控浏览器resize

防抖和节流的区别:

  • 防抖:在n秒时间内,不停的被触发,只执行最后一次

  • 节流:在n秒时间内,不停的被触发,只执行第一次


JavaScript 实现防抖和节流:

防抖实现:

简易版实现

function debounce(func, wait) {
    let timeout;
    return function () {
        const context = this;
        const args = arguments;
        clearTimeout(timeout)
        timeout = setTimeout(function(){
            func.apply(context, args)
        }, wait);
    }
}
// 示例用法
const debouncedFn = debounce(() => {
  console.log('Debounced function executed');
}, 300);

// 调用防抖函数
debouncedFn();
下面代码对this和arguments进行详细解释
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="myButton" onclick="debouncedFn('你好', '世界')">按钮</button>
</body>
<script>
    function debounce(func, wait) {
        let timeout;
        return function () {
            const context = this;
            const args = arguments;
            console.log(this); // 指向按钮元素
            console.log(arguments); // 包含 '你好' 和 '世界'
            
            // 普通函数
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                console.log(this); // 非严格模式下是 window,严格模式下是 undefined
                console.log(arguments); // 空的,因为 setTimeout 回调函数没有参数
                func.apply(context, args);
                // func.call(context, ...args); // 使用 call 代替 apply
                // func.bind(context, ...args)(); // 使用 bind 代替 apply
            }, wait);
 
            // 箭头函数
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                console.log(this); // 指向按钮元素,继承自外层的 `this`
                console.log(arguments); // 包含 '你好' 和 '世界',继承自外层的 `arguments`
                func.apply(context, args);
                // func.apply(this, args);
            }, wait);
        }
    }
 
    function greet(greeting, name) {
        console.log(arguments); // 包含 '你好' 和 '世界'
        console.log(`${greeting}, ${name}!`);
    }
 
    const debouncedFn = debounce(greet, 300);
    console.log(this); // 在全局上下文中,指向全局对象 window
</script>
</html>

立即执行版实现(有时希望立刻执行函数,然后等到停止触发 n 秒后,才可以重新触发执行。)

// 有时希望立刻执行函数,然后等到停止触发 n 秒后,才可以重新触发执行。
function debounce(func, wait, immediate) {
  let timeout;
  return function () {
    const context = this;
    const args = arguments;
    if (timeout) clearTimeout(timeout);
    if (immediate) {
      const callNow = !timeout;
      timeout = setTimeout(function () {
        timeout = null;
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      timeout = setTimeout(function () {
        func.apply(context, args)
      }, wait);
    }
  }
}

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

function debounce(func, wait, immediate) {
  let timeout, result;
  return function () {
    const context = this;
    const args = arguments;
    if (timeout) clearTimeout(timeout);
    if (immediate) {
      const 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;
  }
}
节流实现:

使用时间戳实现(使用时间戳,当触发事件的时候,我们取出当前的时间戳,然后减去之前的时间戳(最一开始值设为 0 ),如果大于设置的时间周期,就执行函数,然后更新时间戳为当前的时间戳,如果小于,就不执行。)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>时间戳节流示例</title>
    <style>
        #content {
            height: 2000px;
            background: linear-gradient(to bottom, #ffefba, #ffffff);
        }
    </style>
</head>
<body>
    <div id="content">
        <h1>滚动页面以查看时间戳节流效果</h1>
    </div>
    <script>
        // 定义节流函数:
        // console.log(lastTime, 'lasttime'); 只在定义 throttle 函数时执行一次,输出 lastTime 的初始值(即 0)。
        // 返回新的节流函数:
        // 返回一个闭包函数,它在每次事件触发时都会执行。
        function throttle(func, wait) {
            let lastTime = 0;
            // 这行只会在函数定义时执行一次
            console.log(lastTime, 'lasttime'); 
            return function () {
                const now = Date.now();
                if (now - lastTime >= wait) {
                    func.apply(this, arguments);
                    lastTime = now;
                    // 这行会在满足条件时执行,即每次节流函数实际执行时
                    console.log(lastTime, 'lasttime---'); 
                }
            };
        }

        function onScroll() {
            console.log('滚动事件触发:', Date.now());
        }

        window.addEventListener('scroll', throttle(onScroll, 5000));
    </script>
</body>
</html>
function throttle(fn, wait = 500, immediate = false) {
    let timer = null, startTime = Date.now(), result = null;
    return function (...args) {
        if(immediate) result = fn.apply(this, args);
        const now = Date.now();
        // 超过了延时时间,马上执行
        if(now - startTime > wait) {
            // 更新开始时间
            startTime = Date.now();
            result = fn.apply(this, args);
        }else {
            // 否则定时指定时间后执行
            if(timer) clearTimeout(timer);
            timer = setTimeout(() => {
            // 更新开始时间
            startTime = Date.now();
            fn.apply(this, args);
            }, wait);
        }
    }
}

// 示例用法
const throttledFn = throttle(() => {
  console.log('Throttled function executed');
}, 300);

// 调用节流函数
throttledFn();

使用定时器实现(当触发事件的时候,我们设置一个定时器,再触发事件的时候,如果定时器存在,就不执行,直到定时器执行,然后执行函数,清空定时器,这样就可以设置下个定时器。)

function throttle(func, wait) {
  let timeout;
  return function () {
    const context = this;
    const args = arguments;
    if (!timeout) {
      timeout = setTimeout(function () {
        timeout = null;
        func.apply(context, args)
      }, wait)
    }

  }
}

涉及的知识点扩展

arguments

在 JavaScript 中,arguments 是一个类数组对象,它在函数内部可用,用于访问传递给函数的所有参数。arguments 不是一个真正的数组,而是一个类似数组的对象,拥有下标和 length 属性,但不具备数组的方法(如 pushpopforEach 等)。

arguments 的主要特点

  1. 类数组对象:

    • arguments 对象类似于数组,但不具备数组的方法。
    • 可以通过下标访问参数,如 arguments[0] 访问第一个参数。
  2. 动态参数数量:

    • arguments 对象可以访问到传递给函数的所有参数,无论参数的数量是固定的还是动态的。
  3. length 属性:

    • arguments.length 属性表示传递给函数的参数个数。

使用示例

基本用法

function example() {
    console.log(arguments); // 类数组对象,包含所有传递的参数
    console.log(arguments[0]); // 第一个参数
    console.log(arguments[1]); // 第二个参数
    console.log(arguments.length); // 参数数量
}

example('a', 'b', 'c');
// 输出:
// { '0': 'a', '1': 'b', '2': 'c', length: 3 }
// 'a'
// 'b'
// 3
 

rest 参数结合

在现代 JavaScript 中,rest 参数(...rest)提供了一种更方便的方式来处理函数参数。rest 参数将所有剩余参数收集到一个真正的数组中,相比于 arguments 对象,它更易于操作。

function example(...rest) {
    console.log(rest); // 真正的数组
    console.log(rest[0]); // 第一个参数
    console.log(rest[1]); // 第二个参数
    console.log(rest.length); // 参数数量
}

example('a', 'b', 'c');
// 输出:
// ['a', 'b', 'c']
// 'a'
// 'b'
// 3

 

arguments 与箭头函数

注意,arguments 对象在箭头函数中是不可用的。箭头函数没有自己的 arguments 对象,它继承了外围函数的 arguments 对象。

function outer() {
    return () => {
        console.log(arguments); // 访问外围函数的 arguments 对象
    };
}

outer(1, 2, 3)(); // 输出: [1, 2, 3]

在上面的代码中,箭头函数 () => { ... } 继承了 outer 函数的 arguments 对象。

总结

  • arguments 是一个类数组对象,提供了对传递给函数的所有参数的访问。
  • rest 参数...rest)在现代 JavaScript 中更为常用,提供了真正的数组并且更易于操作。
  • 箭头函数 不拥有自己的 arguments 对象,而是继承自外围函数。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值