throttle.js 785 B

1234567891011121314151617181920212223242526272829303132
  1. export function debounce(callback, delay) {
  2. let timer;
  3. return function () {
  4. if (timer) {
  5. return;
  6. }
  7. callback.apply(this, arguments);
  8. timer = setTimeout(() => (timer = null), delay);
  9. };
  10. }
  11. export function throttle(callback, delay) {
  12. let isThrottled = false;
  13. let args;
  14. let context;
  15. function wrapper() {
  16. if (isThrottled) {
  17. args = arguments;
  18. context = this;
  19. return;
  20. }
  21. isThrottled = true;
  22. callback.apply(this, arguments);
  23. setTimeout(() => {
  24. isThrottled = false;
  25. if (args) {
  26. wrapper.apply(context, args);
  27. args = context = null;
  28. }
  29. }, delay);
  30. }
  31. return wrapper;
  32. }