防抖

在指定的时间内只触发一次,如果在指定的时候再次触发,将重新计时

  1. const clearTimer = (timer) => {
  2. if (timer !== null) clearTimeout(timer);
  3. return null;
  4. };
  5. // 非立即执行
  6. function debounce(fn, time) {
  7. let timer = null;
  8. return function() {
  9. let content = this;
  10. let args = arguments;
  11. timer = clearTimer(timer);
  12. timer = setTimeout(() => {
  13. timer = clearTimer(timer);
  14. fn.apply(content, args);
  15. }, time);
  16. }
  17. }
  1. const clearTimer = (timer) => {
  2. if (timer !== null) clearTimeout(timer);
  3. return null;
  4. };
  5. // 立即执行
  6. function debounce1(fn, time, immediate) {
  7. let timer = null;
  8. return function() {
  9. let callNow = !timer && immediate;
  10. let content = this;
  11. let args = arguments;
  12. timer = clearTimer(timer);
  13. timer = setTimeout(() => {
  14. timer = clearTimer(timer);
  15. if (!immediate) fn.apply(content, args);
  16. }, time);
  17. if (callNow) fn.apply(content, args);
  18. }
  19. }

节流

降频,稀释执行的频率。降低执行的频率。

浏览器滚动条事件,默认触发频率是 5 ~7 ms 触发一次。

  1. // 时间戳版本
  2. function throttle(func, wait) {
  3. let preTime = 0;
  4. return function() {
  5. let now = Date.now();
  6. let content = this;
  7. let args = arguments;
  8. if (now - preTime > wait) {
  9. func.apply(content, args);
  10. preTime = now;
  11. }
  12. }
  13. }
  1. // 定时器版本
  2. function throttle(func, wait) {
  3. let timer = null;
  4. return function() {
  5. let content = this;
  6. let args = arguments;
  7. if (!timer) {
  8. timer = setTimeout(() => {
  9. timer = null;
  10. clearTimeout(timer);
  11. func.apply(content, args);
  12. }, wait);
  13. }
  14. }
  15. }