Js 防抖、节流设计

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Js节流防抖</title>
    <style>
        #root{
            width:200px;
            height:200px;
            background-color: #ccc;
        }
    </style>

    
</head>
<body>
    <div id="root">

    </div>


    <script>
            var root = document.querySelector('#root');
            var content = 0;
            var timeout;

            var write = function(){
                content++;
                this.innerHTML = content;
            }

            var debounce = function(fn,wait,flag){
                return function(){
                    var __self = this;
                    clearTimeout(timeout);

                    if(flag){
                        
                        var callNow = !timeout;//通过timeout 的真假,控制函数 fn 执行 

                        timeout =  setTimeout(function(){
                            timeout = null;
                        },wait);

                        if(callNow){
                            fn.apply(__self);
                        }

                    }else{  
                        timeout =  setTimeout(function(){
                            fn.apply(__self);
                        },wait);  
                    }
                }
            }

            //开始边界 鼠标进去,立马加1  
            //结束边界  鼠标进去,1秒后加1

            //root.onmousemove = debounce(write,600,true);
            
            var throttle = function(fn,wait){
                var pre = 0;
                return function(){
                    var now = +new Date();
                    var self =this;
                    if(now - pre > wait){
                        fn.apply(self);
                        pre = now;
                    }
                }
                
            }

            //root.onmousemove = debounce(write,600,true);//开源
            root.onmousemove = throttle(write,600);//节流


        
        </script>
</body>
</html>

欢迎关注:http://www.w3schools.top/  学习您想要的一切IT教程!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值