util.js 620 B

123456789101112131415161718192021222324252627282930313233
  1. // 节流
  2. export function throttle(fn, wait = 200) {
  3. let last, timer, now;
  4. return function() {
  5. now = Date.now();
  6. if (last && now - last < wait) {
  7. clearTimeout(timer);
  8. timer = setTimeout(function() {
  9. last = now;
  10. fn.call(this, ...arguments);
  11. }, wait);
  12. } else {
  13. last = now;
  14. fn.call(this, ...arguments);
  15. }
  16. };
  17. }
  18. // 防抖
  19. export function debounce(fn, wait = 200) {
  20. let timer;
  21. return function() {
  22. let context = this;
  23. let args = arguments;
  24. if (timer) clearTimeout(timer);
  25. timer = setTimeout(() => {
  26. fn.apply(context, args);
  27. }, wait)
  28. }
  29. }
  30. export default {
  31. throttle,
  32. debounce
  33. }