zoukankan      html  css  js  c++  java
  • js 防抖和节流,封装成函数

    <!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>
    <button id="s1" style=" 100px;height: 100px;background-color: pink;">
    </button>
    <button id="s2" style=" 100px;height: 100px;background-color: pink;">
    </button>
    </body>
    
    <script>
        // 防抖:同一个事件在某个时间段内被触发多次,只执行最后一次事件
        // 节流:同一个事件在某个时间段内被触发多次,在这个时间段内只执行一次
        let count = 0
        let s1 = document.getElementById("s1")
        //debounce 防抖
    
        debounce = function (func, wait) {
            //由于debounce是这样被调用 s1.onmousemove = debounce(add,300)
            //所以let timeout=null只在加载时执行一次
            let timeout = null
            console.log("hhh")
            //需要return function (),否则下面的 s1.onmousemove = debounce(add) 在页面加载时会直接调用
            return () => {
                // console.log("timeout"+timeout)
                if (timeout) {
                    clearTimeout(timeout)
                }
                timeout = setTimeout(() => {
                    func.apply(this)
                    //func()也可以
                }, wait)
            }
        }
        add = () => {
            console.log(this)
            s1.innerText = count
            count++;
        }
    
        //鼠标在s1对应的节点上滑动时触发
        s1.onmousemove = debounce(add, 300)
        // throttle节流
    
        let s2 = document.getElementById("s2")
    
        throttle = (func, wait) => {
            let flag = true
            return () => {
                if (flag) {
                    setTimeout(() => {
                        func()
                        flag = true
                    }, wait);
                    flag = false
                }
            }
        }
        s2.onmousemove = throttle(add, 1000)
    </script>
    </html>
    
    
  • 相关阅读:
    linux下硬盘分区、格式化以及文件管理系统
    linux下的文档处理及tar命令
    linux文件及目录的权限管理
    linux用户和群组
    linux下mysql的安装与使用
    linux上uwsgi+nginx+django发布项目
    linux虚拟环境搭建
    linux目录文件操作
    linux基本命令
    rbac组件之权限初始化(五)
  • 原文地址:https://www.cnblogs.com/yloved/p/13167201.html
Copyright © 2011-2022 走看看