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

    防抖(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)
    })

    应用场景:

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

    对比

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

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

  • 相关阅读:
    Grid表格的js触发事件
    C# 在获得鼠标点击事件时,如何判断Control键,Shift键被按下
    纠错《COM技术内幕》之ProgID
    C# 日期格式化
    C# 操作系统防火墙
    C# 开发和调用Web Service
    谓侠
    高维FWT
    单位根反演
    容斥 反演
  • 原文地址:https://www.cnblogs.com/lianglanlan/p/14432037.html
Copyright © 2011-2022 走看看