JavaScript实战笔记(一) 防抖与节流函数

对于某些 高频触发 的事件,如果事件处理函数的调用频率没有限制的话,那么将会大大加重浏览器的负担

这时我们可以采用防抖函数或节流函数,减少事件处理函数的调用频率,同时保证不会影响用户体验

1、防抖函数

(1)描述

在触发事件 n 秒后,才会执行事件处理函数,如果 n 秒内再次触发,那么重新计时

(2)实现

function debounce(handler, delay) {
    var timer = null
    return function () {
        var that = this
        var args = arguments
        if (timer) clearTimeout(timer)
        timer = setTimeout(function() { handler.apply(that, args) }, delay)
    }
}

(3)测试

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Debounce</title>
    <script>
        function debounce(handler, delay) { // 防抖函数
            var timer = null
            return function () {
                var that = this
                var args = arguments
                if (timer) clearTimeout(timer)
                timer = setTimeout(function() { handler.apply(that, args) }, delay)
            }
        }
        function show() { // 代理 log 方法
            console.log.apply(console, arguments)
        }
        let debounce_show = debounce(show, 1000)
    </script>
</head>
<body>
    <button onclick="debounce_show('Hello', 'World')">Debounce</button>
</body>
</html>

2、节流函数

(1)描述

防抖函数有一个问题,假如这个事件一直触发,那么这个事件的处理函数将永远无法执行

而使用节流函数可以解决这个问题,当持续触发事件时,节流函数可以保证一定时间内调用一次处理函数

(2)实现

function throttle(handler, waitTime) {
    var timer = null
    var lastTime = Date.now()
    return function () {
        var that = this
        var args = arguments
        var currTime = Date.now()
        var remaining = waitTime - (currTime - lastTime)
        if (timer) clearTimeout(timer)
        if (remaining <= 0) {
            handler.apply(that, args)
            lastTime = Date.now()
        } else {
            timer = setTimeout(function() { handler.apply(that, args) }, waitTime)
        }
    }
}

(3)测试

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Debounce</title>
    <script>
        function throttle(handler, waitTime) { // 节流函数
            var timer = null
            var lastTime = Date.now()
            return function () {
                var that = this
                var args = arguments
                var currTime = Date.now()
                var remaining = waitTime - (currTime - lastTime)
                if (timer) clearTimeout(timer)
                if (remaining <= 0) {
                    handler.apply(that, args)
                    lastTime = Date.now()
                } else {
                    timer = setTimeout(function() { handler.apply(that, args) }, waitTime)
                }
            }
        }
        function show() { // 代理 log 方法
            console.log.apply(console, arguments)
        }
        let throttle_show = throttle(show, 1000)
    </script>
</head>
<body>
    <button onclick="throttle_show('Hello', 'World')">Throttle</button>
</body>
</html>

【 阅读更多 JavaScript 系列文章,请看 JavaScript学习笔记

猜你喜欢

转载自www.cnblogs.com/wsmrzx/p/12206245.html