zoukankan      html  css  js  c++  java
  • 防抖和节流

    防抖(debounce)

    防抖即防止抖动,避免把一次事件误认为多次,应用的场景有:

    • 登录,发短信,抢购按钮避免用户点击过快导致发送多次请求
    • 调整浏览器窗口大小
    • 在线编辑器停止输入后一定时长保存内容
    • 实时输入搜索
    • ...

    防抖的重点在于清零,将之前所有的操作清零,只保留最后一次操作。

    function debounce(fn, wait) {
        let timer;
        return (...args) => {
            clearInterval(timer);
            timer = setTimeout(() => {
                fn(...args);
            }, wait);
        }
    }
    

    节流(throttle)

    节流的主要目的在于降低频率,将高频事件转换为低频事件。应用场景有:

    • scroll事件
    • 轮播图的点击切换
    • 播放事件,每一秒计算进度信息
    • ...

    节流的重点在于加锁,一定时间段内只触发一次操作。

    function throttle(fn, wait) {
        let timer = null;
        return (...args) => {
            if (timer !== null) return;
            timer = setTimeout(() => {
                fn(...args);
                timer = null;
            }, wait);
        }
    }
    

    [参考资料] https://q.shanyue.tech/fe/js/3.html

  • 相关阅读:
    牛客算法周周练18A
    洛谷P2580
    Codeforces 617E
    SPOJ 3267
    Codeforces Round #661 (Div. 3) 解题报告(ABCD)
    Codeforces 1399D
    Codeforces 1399C
    Codeforces 1399B
    Codeforces 1399A
    牛客算法周周练18 解题报告(ABCE)
  • 原文地址:https://www.cnblogs.com/hycstar/p/14626640.html
Copyright © 2011-2022 走看看