zoukankan      html  css  js  c++  java
  • 移动端事件(五)—— 函数防抖和函数节流的封装

    我们了解了函数防抖与函数节流的思路后,我们现在来将他们封装起来,提高代码复用性。

    今天直接上菜

      cb 要处理防抖的函数
      time 默认的高频间隔时间
      isStart 是否在头部执行

    函数防抖封装:调用debounce 函数,返回一个处理过防抖的函数

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            #box {
                width: 300px;
                height: 400px;
                background: red;
            }
        </style>
    </head>
    <body>
    <div id="box"></div>    
    <script>
    
    function debounce(cb,delay = 200,isStart = false){
        let timer = 0;
        let isFirst = true; //是否是第一次执行
        return function(...arg){
            clearTimeout(timer);
            if(isFirst&&isStart){
                cb.apply(this,arg);
                isFirst = false;
            }
            timer = setTimeout(()=>{
                (!isStart)&&cb.apply(this,arg);
                isFirst = true;
            },delay)
        }
    }
    
    box.onmousemove = debounce((e)=>{
        console.log(1);
    },200,true);
    </script>    
    </body>
    </html>

    函数节流封装:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            #box {
                width: 300px;
                height: 400px;
                background: red;
            }
        </style>
    </head>
    <body>
    <div id="box"></div>    
    <script>
    function throttle(cb,interval=200,isStart=false){
        let timer = 0;
        return function(...arg){
            if(timer){
                return ;
            }
            isStart&&cb.apply(this,arg);
            timer = setTimeout(()=>{
                (!isStart)&&cb.apply(this,arg);
                timer = 0;
            },interval)
        }
    }
    box.onmousemove = throttle(function(e){
        console.log(1,e,this);
    },500)   
    </script>    
    </body>
    </html>

    以上的封装都是可以直接使用的,有兴趣的看上一篇文章了解函数防抖与函数节流的思路会更好。

    移动端到此也就告一段落了。

  • 相关阅读:
    bootStrap-treeview插件
    UML常用图的几种关系的总结
    RFC中文文档
    继承:重新使用接口
    Java8向后兼容
    Java8 时间调节器
    Java8 ChronoUnits枚举
    BigDecimal.divide方法
    java.lang.Double.byteValue() 方法
    事件处理是什么?
  • 原文地址:https://www.cnblogs.com/jfen625/p/12563153.html
Copyright © 2011-2022 走看看