underscore防抖实现

71 阅读1分钟

【若川视野-源码阅读】第25期【underscore-debounce】[跟着underscore学防抖]=(www.yuque.com/ruochuan12/…)

<!DOCTYPE html>
<html lang="zh-cmn-Hans">

<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge, chrome=1">
    <title>debounce</title>
    <style>
        #container{
            width: 100%; height: 200px; line-height: 200px; text-align: center; color: #fff; background-color: #444; font-size: 30px;
        }
    </style>
</head>

<body>
    <div id="container"></div>
    <script>
        /**
         * func: 需要执行的方法
         * wait: 间隔触发时常 
         *       immediate = true,效果是停止触发事件后,等待wait毫秒,才能再次触发效果,使用场景: 下拉加载等
         *       immediate = false,效果是停止触发事件后,等待wait毫秒,效果执行,使用场景: 输入框等
         * immediate: 是否直接执行
        */
        function debounce(func, wait, immediate) {
            // 需要记录this指向 context
            // 记录入参 args
            // 记录倒计时名称 timeout
            // 记录返回结果 result
            let context, args, timeout, result;

            context = this

            function immediateHandler(){
                if(!timeout){
                    result = func.apply(context,args)
                }
                
                timeout = setTimeout(()=>{
                    timeout = null
                },wait)
            }
            // 
            function debounced(){
                args = arguments
                if(timeout){
                    clearTimeout(timeout)
                }
               
                if(immediate){
                    // 走直接触发
                    immediateHandler()
                }else{
                   
                    timeout = setTimeout(()=>{
                        result = func.apply(context,args)
                    },wait)
                }

                return result

            }

            debounced.clear = function (){
                clearTimeout(timeout)
                timeout = null
            }

            return debounced;
        }

        var count = 1;

        var container = document.getElementById('container');

        function getUserAction(e) {
            console.log(e.clientX,'e.clientX')
            console.log('出发')
            container.innerHTML = count++;
        };


        // container.onmousemove = debounce(getUserAction,3000,true);
        container.onmousemove = debounce(getUserAction,300);

    </script>



</body>

</html>