anitthro.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. let timer1 = null; //防抖,
  2. let timer2 = null; //节流
  3. function Debounce(fn, t) {//防抖
  4. let delay = t || 500;
  5. let timer1 = null; // 收敛进闭包:每个防抖实例独立计时,避免全局 timer1 被其它调用 clearTimeout 互相取消
  6. return function () {
  7. let args = arguments;
  8. // let timer1 = null
  9. // console.log(timer1);
  10. if(timer1){
  11. clearTimeout(timer1);
  12. }
  13. timer1 = setTimeout(() => {
  14. fn.apply(this, args);
  15. timer1 = null;
  16. }, delay);
  17. }
  18. }
  19. // 使用
  20. /*import {Debounce} from '@/common/debounceThrottle.js'
  21. Debounce(() => {
  22. //要执行的函数
  23. }, 200)() */
  24. function Throttle(fn, t) {//节流
  25. let last;
  26. let interval = t || 500;
  27. return function () {
  28. let args = arguments;
  29. let now = +new Date();
  30. if (last && now - last < interval) {
  31. clearTimeout(timer2);
  32. timer2 = setTimeout(() => {
  33. last = now;
  34. fn.apply(this, args);
  35. }, interval);
  36. } else {
  37. last = now;
  38. fn.apply(this, args);
  39. }
  40. }
  41. }
  42. module.exports = {
  43. Debounce: Debounce,
  44. Throttle: Throttle
  45. }