函数防抖

时间:2021-07-15
本文章向大家介绍函数防抖,主要包括函数防抖使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        html,body{
            height: 300%;
            /* background:-webkit-linear-gradient(top left,lightblue,lightgreen,orange ); */
            background: #fff;
        }

        #submit{
            margin: 50px;
        }
    </style>
</head>
<body>
    <button id="submit">提交</button>

    <script>

        /**
         * (防抖) 对于频繁触发某个操作 只识别一次
         *  func 执行函数
         *  wait  number 设置频繁操作的时间
         *  innediate boolean 默认多次操作,识别最后一次操作
         * 
         * @return  
         *    可以被调用的 函数
         * */   
        function debounce(func,wait = 300,innediate = false){
            let timer = null;
            return function anoymous(...params){ 
                let now = innediate && !timer;
                clearTimeout(timer);  // 每次点击之前都把定时器 清除 
                // 重新设置定时器
                timer = setTimeout(() => {  
                    // 设置为初始状态
                    timer = null;
                    !innediate ? func.call(this,...params) : null;
                },wait); 
                // 如果是立即执行
                now ? func.call(this,...params) : null;
            }

        }

        function handle(){
            // 设置定时器 
            console.log('ok'); 
        }

        // submit.onclick = handle; 
        submit.onclick = debounce(handle,500,true) 

    </script>
</body>
</html>
我是Eric,手机号是13522679763

原文地址:https://www.cnblogs.com/eric-share/p/15015858.html