再学JS--事件防抖

作者: Territory_Cheng | 来源:发表于2020-07-16 18:04 被阅读0次

在前端开发中会遇到一些频繁的事件触发,例如:

  1. window的resize、scroll
  2. mousedown、mousemove
  3. keyup、keydown

频繁的触发会造成卡顿现象,为了解决这个问题,一般有两种解决方案:

  1. debounce防抖
  2. throttle节流

防抖

防抖的原理是:你尽管触发事件,但是我一定在事件触发n秒后执行,如果一个事件触发n秒内又触发了这个事件,那我就以新的事件的时间为准,n秒后执行,总之就是要等你触发事件n秒内不再触发事件。

<html>
<head>
    <meta charset="utf-8">

    <style>
        #container {
            width: 100%;
            height: 200px;
            line-height: 200px;
            text-align: center;
            color: #000;
            background-color: #ddd;
        }
    </style>
</head>

<body>
    <div id="container"></div>
</body>

<script>
    var count = 1;
    var container = document.getElementById('container')

    function getUserAction() {
        container.innerHTML = count++
    }

    container.onmousemove = getUserAction
</script>

</html>

第一版

function debounce(func, wait) {
    var timeout
    return function() {
        clearTimeout(timeout)
        timeout = setTimeout(func, wait)
    }
}

this

getUserAction函数中,在不使用debounce时,this指向的是container的dom元素,在使用debounce时,this指向的是window,修改下代码修正this指向

function debounce(func, wait) {
    var timeout
    return function() {
        var context = this
        clearTimeout(timeout)
        timeout = setTimeout(function() {
            func.apply(context)
        }, wait)
    }
}

event对象

JavaScript在事件处理函数中会提供事件对象event,但在使用debounce时,event对象为undefined,修正下event对象问题

function debounce(func, wait) {
    var timeout
    return function() {
        var context = this
        var args = arguments

        clearTimeout(timeout)
        timeout = setTimeout(function() {
            func.apply(context, args)
        }, wait)
    }
}

返回值

getUserAction函数可能存在返回值,所以我们要返回函数执行的结果

function debounce(func, wait) {
    var timeout, reslut
    return function() {
        var context = this
        var args = arguments

        clearTimeout(timeout)
        timeout = setTimeout(function() {
            reslut = func.apply(context, args)
        }, wait)
        
        return reslut
    }
}

立即执行

立即执行需求是,我不想非要等到事件停止触发后才执行,我希望能立即执行函数,然后等到停止触发n秒后,才可以重新执行

function debounce(func, wait, immediate) {
    var timeout, reslut
    
    return function() {
        var context = this
        var args = arguments

        if(timeout) clearTimeout(timeout)

        if(immediate) {
            // 如果已经执行过,不再执行
            var callNow = !timeout
            timeout = setTimeout(function() {
                timeout = null
            }, wait)
            if(callNow) reslut = func.apply(context, args)
        } else {
            timeout = setTimeout(function() {
                reslut = func.apply(context, args)
            }, wait)
        }

        return reslut
    }
}

取消

可以支持取消debounce函数,比如说我debounce的时间为10秒,immediate为true,这样的话,我只有等10秒之后才能重新触发事件,现在我希望能主动取消debounce,可以再次触发函数

function debounce(func, wait, immediate) {
    var timeout, reslut
    var debounced = function() {
        var context = this
        var args = arguments

        if(timeout) clearTimeout(timeout)

        if(immediate) {
            // 如果已经执行过,不再执行
            var callNow = !timeout
            timeout = setTimeout(function() {
                timeout = null
            }, wait)
            if(callNow) reslut = func.apply(context, args)
        } else {
            timeout = setTimeout(function() {
                reslut = func.apply(context, args)
            }, wait)
        }

        return reslut
    }

    debounced.cancel = function() {
        clearTimeout(timeout)
        timeout = null
    }

    return debounced
}

完整示例代码

<html>
<head>
    <meta charset="utf-8">

    <style>
        #container {
            width: 100%;
            height: 200px;
            line-height: 200px;
            text-align: center;
            color: #000;
            background-color: #ddd;
        }
    </style>
</head>

<body>
    <div id="container"></div>
    <button id="cancel">取消</button>
</body>

<script>
    var count = 1;
    var container = document.getElementById('container')
    var cancel = document.getElementById('cancel')

    function getUserAction(e) {
        container.innerHTML = count++
        console.log(e)
    }

    var debounceFun = debounce(getUserAction, 10000, true)

    container.onmousemove = debounceFun

    cancel.onclick = function() {
        debounceFun.cancel()
    }

    function debounce(func, wait, immediate) {
        var timeout, reslut
        var debounced = function() {
            var context = this
            var args = arguments
            
            if(timeout) clearTimeout(timeout)

            if(immediate) {
                // 如果已经执行过,不再执行
                var callNow = !timeout
                timeout = setTimeout(function() {
                    timeout = null
                }, wait)
                if(callNow) reslut = func.apply(context, args)
            } else {
                timeout = setTimeout(function() {
                    reslut = func.apply(context, args)
                }, wait)
            }
    
            return reslut
        }

        debounced.cancel = function() {
            clearTimeout(timeout)
            timeout = null
        }

        return debounced
    }

</script>

</html>

相关文章

  • 再学JS--事件防抖

    在前端开发中会遇到一些频繁的事件触发,例如: window的resize、scroll mousedown、mou...

  • 再学JS--事件节流

    节流 节流:如果你持续触发事件,每隔一段时间,只执行一次事件 关于节流的实现,有两种主流的实现方式,一种是使用时间...

  • 手写防抖节流函数

    1. 防抖 1.1 什么是防抖? ​ 防抖是触发高频事件后,n秒内函数只会执行一次, 如果n秒内高频事件再次触...

  • 防抖与节流

    1. 防抖函数 1.1 防抖定义: 函数防抖(debounce):当持续触发事件时(例如mousemove),一定...

  • 面试过程中遇到的问题记录

    1.js的防抖和节流 函数防抖 函数防抖原理(debounce):当持续触发事件时,一定时间段内没有再触发事件,事...

  • 防抖节流的实现和防抖函数的封装

    防抖 防抖即“防止抖动”,当我们频繁触发一个事件时,每次事件都会执行,会造成不必要的性能损失。 防抖就是要延迟执行...

  • 防抖和节流(防止前端触发多次事件)

    防抖 防抖触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。防抖的原理就是:你尽...

  • 2020-04-28

    #JS中的防抖和节流 1、防抖 对于短时间内连续触发的事件(上面的滚动事件),防抖的含义就是让某个时间期限(如上面...

  • JS函数防抖

    JS 中的函数防抖 一、什么是函数防抖? 概念: 函数防抖(debounce), 就是指触发事件后,在 n 秒内函...

  • 防抖和节流

    定义 什么是防抖与节流? 防抖(debounce):当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会...

网友评论

    本文标题:再学JS--事件防抖

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