1. 程式人生 > 實用技巧 >關於Js debounce(防抖)函式小結

關於Js debounce(防抖)函式小結

閉包的實際運用防抖

防抖:當持續觸發事件時,一定時間段內沒有再觸發事件,事件處理函式才會執行一次,
如果設定的時間到來之前,又一次觸發了事件,就重新開始 延時。
(如果在一段時間內,又觸發了該事件;就重新開始 延時)
主要運用
1==>在使用者輸入
2==> 使用者不斷的點選按鈕
3==>射擊遊戲中的mousedown、keydown事件

節流:在規定時間內,保證執行一次該函式。

將函式呼叫賦值給變數;此時函式已經執行了一次哈

你認為test函式有沒有被執行
   <script>
        function test() {
            console.log('我是被執行了一次的');
        }
        let aa = test(); 
    </script>

已經執行了
//將函式呼叫賦值給變數;此時函式已經執行了一次哈
<!DOCTYPE html>
<html lang="en">

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

<body>
    <input type="text" id="input">
    <script>
        function debounce(func, delay) {
            console.log(1)
            let timer;
            return function (args) {
                clearInterval(timer);
                timer = setTimeout(function () {
                    // 在delay秒內執行某一個func事件;
                    func(args)
                }, delay)
            }
        }

        function inputFunction(val) {
            console.log(`你輸出的結束是${val}`);
        }

        //此時的防抖函式已經被執行過一次了;在賦值的過程中;
        const debouceInput = debounce(inputFunction, 500);


        const input = document.getElementById("input");
        input.addEventListener('keyup', function (e) {
            debouceInput(e.target.value)
        })
    </script>
</body>

</html>