如何实现中文防抖

如何实现中文防抖markdown

防抖:动做绑定事件,动做发生后必定时间后触发事件,在这段时间内,若是该动做又发生,则从新等待必定时间再触发事件。 防抖的简单封装:闭包

function debounce(fn,delay) {
  // timer在闭包中,
  let timer = null;
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.call(this, arguments);
      timer = null;
    }, delay);
  };
}
复制代码

在输入框中使用防抖测试

const userName = document.getElementById('username');
userName.addEventListener('keyup', debounce(function() {
  console.log(this.value);
}, 1000));
复制代码

上面这种封装和用法只能适用input输入非中文内容。若是咱们在输入中文的时候就会有一些问题,尚未肯定中文内容,可是定时器已经到时间了。就会触发后续的操做。this

针对输入中文字符实现防抖spa

function debounce(fn, delay) {
  let timer = null;
  return function(e) {
    if (e.target.composing) {
      return;
    }
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.call(this, arguments);
      timer = null;
    }, delay);
  };
}

function compositionStart(e) {
  e.target.composing = true;
}

function compositionEnd(e) {
  e.target.composing = false;
  const event = document.createEvent('HTMLEvents');

  event.initEvent('input');
  e.target.dispatchEvent(event);
}
复制代码

测试中文防抖code

const userName = document.getElementById('username');
userName.addEventListener('keyup', debounce(function(e){
  console.log(this.value);
}, 2000));

userName.addEventListener('compositionstart', compositionStart);
userName.addEventListener('compositionend', compositionEnd);
复制代码

提到防抖,咱们就不得不想起节流,orm

节流: 动做绑定事件,动做发生后一段时间后触发事件,在这段时间内,若是动做又发生,则无视该动做,直到事件执行完后,才能从新触发。 防抖的简单封装:事件

function throttle(fn, delay) {
  let timer = null;
  return function () {
    if (timer) {
      return;
    }
    timer = setTimeout(() => {
      fn.call(this, arguments);
      timer = null;
    }, delay);
  };
}
```/
复制代码
相关文章
相关标签/搜索