Js函数防抖

2020-12-15  本文已影响0人  HueyYao

把这段代码放置到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/

上一篇下一篇

猜你喜欢

热点阅读