美文网首页
Js函数防抖

Js函数防抖

作者: HueyYao | 来源:发表于2020-12-15 23:00 被阅读0次

    把这段代码放置到html界面中 通过查看log打印的内容来感受变化

    
    window.addEventListener("resize",debounce(handle,2000));
    
    function handle(){
        console.log(Math.random());
    }
    
    function debounce(fn,wait){
        var timer = null;
        return function(){
            if(timer !== null){
                clearTimeout(timer);
            }
            timer = setTimeout(fn,wait);
        }
    }
       
    

    同时推荐一种目前使用的方式这种方式来实现防抖动功能

    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.19/lodash.min.js"></script>
    <input type="text" id="keywords" value="" placeholder="请输入用户名">
    <script>
        var debounce = _.debounce(changeGold, 1000);
        document.getElementById("keywords").onkeyup = debounce
        function changeGold() {
            console.log(document.getElementById("keywords").value);
        }
    </script>
    

    参考文章:http://www.884358.com/lodash-debounce-throttle/

    相关文章

      网友评论

          本文标题:Js函数防抖

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