throttle.js 696 B

1234567891011121314151617181920212223242526272829303132
  1. /**
  2. * @desc 函数节流
  3. * @param func 函数
  4. * @param wait 延迟执行毫秒数
  5. * @param type 1 表时间戳版,2 表定时器版
  6. */
  7. export const throttle = (func, wait, type) => {
  8. if (type === 1) {
  9. var previous = 0;
  10. } else if (type === 2) {
  11. var timeout;
  12. }
  13. return function() {
  14. let context = this;
  15. let args = arguments;
  16. if (type === 1) {
  17. let now = Date.now();
  18. if (now - previous > wait) {
  19. func.apply(context, args);
  20. previous = now;
  21. }
  22. } else if (type === 2) {
  23. if (!timeout) {
  24. timeout = setTimeout(() => {
  25. timeout = null;
  26. func.apply(context, args);
  27. }, wait);
  28. }
  29. }
  30. };
  31. };