防抖和节流

时间:2020-01-06 20:41:07   收藏:0   阅读:75

什么时候使用防抖,比如在输入框输入文字进行联想搜索,不可能输入一下就搜索一次,所以就用到了防抖

<input id="phone" type="text"/>
// 需要触发搜索的函数
function debounce(d){
    console.log("联想搜索phoneNumber:" + d)
}
let inp = document.querySelector("#phone");
// 输入触发的事件
function getPhone(fn,delay){
    let timer;
    // 使用闭包,保证每次使用的定时器是同一个
    return (d)=>{
        clearTimeout(timer);
        timer = setTimeout(()=>{
            fn(d);
            // 结束之后清除定时器
            clearTimeout(timer);
        },delay)
    }
}

let getPhoneDebounce = getPhone(debounce,1000);

inp.addEventListener(keyup,(e)=>{
    getPhoneDebounce(e.target.value);
})

节流请见下回分解

原文:https://www.cnblogs.com/Chauncy-SHI/p/12157727.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!