AI销管
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

33 lines
770 B

  1. let timer, flag;
  2. /**
  3. * 节流原理:在一定时间内,只能触发一次
  4. *
  5. * @param {Function} func 要执行的回调函数
  6. * @param {Number} wait 延时的时间
  7. * @param {Boolean} immediate 是否立即执行
  8. * @return null
  9. */
  10. function throttle(func, wait = 500, immediate = true) {
  11. if (immediate) {
  12. if (!flag) {
  13. flag = true;
  14. // 如果是立即执行,则在wait毫秒内开始时执行
  15. typeof func === 'function' && func();
  16. timer = setTimeout(() => {
  17. flag = false;
  18. }, wait);
  19. }
  20. } else {
  21. if (!flag) {
  22. flag = true
  23. // 如果是非立即执行,则在wait毫秒内的结束处执行
  24. timer = setTimeout(() => {
  25. flag = false
  26. typeof func === 'function' && func();
  27. }, wait);
  28. }
  29. }
  30. };
  31. export default throttle