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.

30 lines
875 B

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