美文网首页
js函数的防抖(debounce)与节流(throttle)

js函数的防抖(debounce)与节流(throttle)

作者: 易冷zzz | 来源:发表于2021-02-20 01:07 被阅读0次

    按照防抖函数和节流函数的定义手动实现该效果,当然功能并不完善还有待改进,详细的请参考原文链接:js 函数的防抖(debounce)与节流(throttle)

    <!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>
    </head>
    <body>
        <div id="box" style="width: 200px;height: 200px;background: #eee;"></div>
        <script>
            let box = document.getElementById('box')
            //防抖函数-开始触发时执行
            /* let flag = true
            box.onmousemove = function () {
                if(flag){
                    console.log(111)
                    flag = false
                }
            } */
            //防抖函数-触发结束时执行
            
            /* box.onmouseenter = function () {
                let flag = true
                box.onmouseleave = function () {
                    if(flag){
                        console.log(111)
                        flag = false
                    }
                }
            } */
    
            //节流
            box.onmouseenter = function () {
                let flag = true
                setInterval(function () {
                    if(flag){
                        console.log(123)
                    }
                }, 2000)
                box.onmouseleave = function () {
                    flag = false
                }
            }
        </script>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:js函数的防抖(debounce)与节流(throttle)

          本文链接:https://www.haomeiwen.com/subject/jqzzxltx.html