一、防抖

当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。
手动实现一个简单的防抖装饰器:

  1. function debounce(fn, ms) {
  2. let timeout;
  3. return function () {
  4. clearTimeout(timeout);
  5. timeout = setTimeout(() => fn.apply(this.arguments), ms);
  6. }
  7. }

二、节流

当持续触发事件时,保证一定时间段内只调用一次事件处理函数。
实现一个简单的节流装饰器:

  1. function throttle(fn, ms) {
  2. let isThrottled = false;
  3. let savedArgs, savedThis;
  4. function wrapper() {
  5. if (isThrottled) {
  6. savedArgs = arguments;
  7. savedThis = this;
  8. return;
  9. }
  10. fn.apply(this, arguments);
  11. isThrottled = true;
  12. setTimeout(function () {
  13. isThrottled = false;
  14. if (savedArgs) {
  15. wrapper.apply(savedThis, savedArgs)
  16. savedArgs = savedThis = null;
  17. }
  18. }, ms)
  19. }
  20. return wrapper;
  21. }