美文网首页
事件节流

事件节流

作者: 吐了节课蝰蛇 | 来源:发表于2020-05-15 22:13 被阅读0次

    如果不希望用户频繁触发某个事件,可以采用事件节流的方法解决,在短时间(可设置)内连续触发,只会执行一次事件。

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <style>
                .div {
                    width: 200px;
                    height: 200px;
                    background-color: red;
                    transition: width 2s linear 0s;
                }
            </style>
        </head>
        <body>
            <div class="div"></div>
        </body>
    </html>
    <script>
        var div = document.querySelectorAll(".div")[0];      
        var num = 0;      
        var t = null;       
        
        //事件累加的功能
        //js 多次触发点击事件,在一定延迟内只执行一次         
        div.onclick = function() {        
            if(t != null) {          
                clearTimeout(t)        
            }        
            t = setTimeout(function() {          
                num++;          
                console.log(num);        
            }, 500)      
        }
    </script>
    

    在低于500毫秒间隔内,连续触发多次点击事件,只会执行一次。

    相关文章

      网友评论

          本文标题:事件节流

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