简介

在 JavaScript 中,防抖(debounce)和节流(throttle)是用来限制函数执行频率的两种常见技术。

防抖(debounce) 是指在某个时间段内,只执行最后一次触发的函数调用。如果在这个时间段内再次触发该函数,会重新计时,直到等待时间结束才会执行函数。
这个技术通常用于处理频繁触发的事件,比如窗口大小调整、搜索框输入等。防抖可以避免函数执行过多次,以减少网络开销和性能负担。

节流(throttle) 是指在一段时间内限制函数的执行频率,保证一定时间内只执行一次函数调用。无论触发频率多高,都会在指定时间间隔内执行一次函数。
这个技术通常用于处理连续触发的事件,比如滚动事件、鼠标移动事件等。节流可以控制函数的执行频率,以减少资源消耗和提高性能。

防抖

image.png

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style></style>
</head>

<body>
    <button>防抖</button>
</body>
<script>
    let button = document.querySelector('button');
    button.onclick = shake(function() {
        console.log('防抖');
    },1000)
    //  防抖函数 
    //  封装防抖函数,参一: 点击的函数 参二: 时间
    function shake(handler, time){
        let timer ;
        return function() {
            //  第一清除定时器
            clearTimeout(timer)
            const _this = this 
            timer = setTimeout(function() {
                handler.call(_this, ...arguments)
            },time)
        }
    }
</script>

</html>

节流

image.png

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style></style>
</head>

<body>
    
</body>
<script>
    // 节流
   document.onmousemove = throttle(function(e) {
    console.log(e.clientX, e.clientY);
   },1000)
   function throttle(handler, time) {
    //  开始时间
    let startTime = +new Date()
    return function() {
        const _this = this
        //  结束时间
        let endTime = +new Date()
        if (endTime - startTime < time){
            return false
        }
        handler.call(_this, ...arguments)
        startTime = endTime
     }
   }
</script>

</html>

道友
1 声望0 粉丝