防抖:

案例:

搜索时在输入框输入内容,频繁的发送请求

解决办法:设置停止输入一段时间之后再发送请求

没有设置防抖

js代码

var text = document.getElementById('write');
function write() {
    console.log(text.value);
}
text.addEventListener('input',write);

效果:

js防抖

会发现当我们不断的输入搜索内容时会不断的发送请求

设置防抖

js代码:

var text = document.getElementById('write');
function denounce(fn,delay) {
    var timer;
    return function () {
        if(timer){
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            fn();
        },delay)
    }
}
function write(){
    console.log(text.value);
}
text.addEventListener('input',denounce(write,1000))

效果:

js防抖

会发现当我们设置了防抖后停止输入1秒后才会执行请求

但是这样做也存在问题:当我们要不断的高频触发一个事件时会导致事件无法触发,比如滚动事件,当我们不断的滚动页面时,由于没到延迟的时间,导致高频时间不能被触发。

相关文章:

  • 2020-03-22
  • 2019-11-12
  • 2021-06-14
  • 2021-10-04
  • 2021-10-05
  • 2021-11-13
猜你喜欢
  • 2022-12-23
  • 2021-11-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-02
相关资源
相似解决方案