• 节流和防抖


    防抖(debounce)

    在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时

    function debounce(func, delay) {
        let timer = null
        return function (...args) {
            if (timer) {
                clearTimeout(timer)
            }
            timer = setTimeout(() => {
                func.apply(this, args)
            }, delay)
        }
    }
    
    //模拟一段ajax请求
    function ajax(content) {
        console.log(`ajax request ${content}`)
    }
    let input = document.getElementById('debounce')
    let debounceAjax = debounce(ajax, 500)
    input.addEventListener('keyup', (e) => {
        debounceAjax(e.target.value)
    })

    应用场景:

    输入框搜索联想,用户在不断输入值时,用防抖来节约请求资源

    window触发resize时,不断调整浏览器窗口大小会不断触发事件,用防抖让其只触发一次

    节流(throttle)

    一个单位时间内,只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效

    function throttle(func, delay) {
        let timer, last
        return function (...args) {
            let now = + new Date()
            if (last && now < last + delay) {
                clearTimeout(timer)
                timer = setTimeout(() => {
                    last = now
                    func.apply(this, args)
                }, delay)
            } else {
                last = now
                func.apply(this, args)
            }
        }
    }
    
    function ajax(content) {
        console.log(`ajax request ${content}`)
    }
    let throttleAjax = throttle(ajax, 1000)
    let input = document.getElementById('throttle')
    input.addEventListener('keyup', (e) => {
        throttleAjax(e.target.value)
    })

    应用场景:

    监听滚动事件,比如是否滑到底部自动加载更多

    对比

    都是防止某一事件频繁触发

    防抖是某一时间段内只执行一次,函数节流是间隔时间执行

  • 相关阅读:
    SqlServer禁用启用触发器、外键约束
    解决Windows Server2008R2中导入Excel不能使用Jet 4.0
    C#读写配置文件
    C#后台如何获取客户端访问系统型号
    Flex在Win10,Chrome浏览器上汉字乱码的问题
    flex lineChart 显示所有的数据节点
    HTTP状态码大全
    zabbix使用sendEmail发送邮件报警
    zabbix安装
    Samba服务器搭建配置
  • 原文地址:https://www.cnblogs.com/lianglanlan/p/14432037.html
Copyright © 2020-2023  润新知