1. 程式人生 > 實用技巧 >JS 函式防抖和節流

JS 函式防抖和節流

在 web 開發中,需要考慮到使用者頻繁點選請求的情況,給伺服器造成壓力,這時候,就可以通過使用函式防抖和節流來減少頻繁點選請求的情況。

函式防抖(debounce)

在 n 秒內連續觸發同一事件,只在最後一次或第一次執行,中間不執行

只在最後一次執行

<script>
    function success() {
        console.log('提交成功');
    }
    function debounce(fn ,delay) {
        let timer = null;
        return () => {
            if(timer)
                clearTimeout(timer);
            timer = setTimeout(() => {
                fn.apply(this, arguments);
            }, delay);
        }
    }
    const debounceHandle = debounce(success, 1000);
    const btn = document.getElementById('btn');
    btn.addEventListener('click', debounceHandle);
</script>    

只在第一次執行

<script>
	function success() {
        console.log('提交成功');
    }
    function debounce(){
        let timer = null;
        return () => {
            if(timer)
                clearTimeOut(timer);
            let callNow = !timer;
            timer = setTimeOut(() => {
                timer = null;
            }, delay);
            if(callNow){
                fn.apply(this, arguments);
            }
        }
    } 
    const debounceHandle = debounce(success, 1000);
    const btn = document.getElementById('btn');
    btn.addEventListener('click', debounceHandle);
</script>

函式節流(throttle)

在 n 秒內連續觸發同一事件,經過一定間隔執行一次

通過時間戳指定間隔

<script>
	function success() {
        console.log('提交成功');
    }
    function throttle(fn ,delay) {
        let pre = 0;
        return () => {
            let now = new Date();
            if(now - pre > delay){
                // 下一次與上一次點選的間隔大於一秒才會執行
                fn.apply(this, arguments);
                pre = now;
            }
        }
    }
    const throttleHandle = throttle(success, 1000);
    const btn = document.getElementById('btn');
    btn.addEventListener('click', throttleHandle);
</script>

通過定時器指定間隔

<script>
	function success() {
        console.log('提交成功');
    }
    function throttle(fn ,delay) {
        let timer = null;
        return () => {
            if(!timer){
                timer = setTimeOut(() => {
                    timer = null;
                    fn.apply(this, arguments);
                }, delay)
            }
        }
    }
    const throttleHandle = throttle(success, 1000);
    const btn = document.getElementById('btn');
    btn.addEventListener('click', throttleHandle);
</script>