美文网首页
防抖与节流

防抖与节流

作者: JsPatric | 来源:发表于2021-04-27 14:38 被阅读0次

    //防抖(debounce):触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。

    const debounce = (func, delay = 200) => {

        let timeout = null

        return function () {

            clearTimeout(timeout)

            timeout = setTimeout(() => {

                func.apply(this, arguments)

                }, delay) }

        }

    const fetch = (e) => {

        console.log('fetch', e)

    }

    const debounceSuggest = debounce(fetch, 500)

    const btn1 = document.getElementById('btn1')btn1.onclick = function (e) {

        debounceSuggest(e)

    }

    //节流(throttle):高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率。

    const throttle = (func, delay = 200) => {

        let timeout = null

        return function () {

        if (!timeout) {

            timeout = setTimeout(() => {

                func.apply(this, arguments)

                clearTimeout(timeout)

                timeout = null }, delay) }

            }

        }

    const throttleSuggest = throttle(fetch, 500)

    const btn2 = document.getElementById('btn2')

    btn2.onclick = function (e) {

        //触发方法

        console.log("click")

        throttleSuggest(e)

    }

    相关文章

      网友评论

          本文标题:防抖与节流

          本文链接:https://www.haomeiwen.com/subject/gfourltx.html