debounce.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. export default function debounce(func, wait, immediate) {
  2. let timeout,
  3. args,
  4. context,
  5. timestamp,
  6. result
  7. function later() {
  8. const last = +(new Date()) - timestamp
  9. if (last < wait && last >= 0) {
  10. timeout = setTimeout(later, wait - last)
  11. } else {
  12. timeout = undefined
  13. if (!immediate) {
  14. result = func.apply(context, args)
  15. if (!timeout) {
  16. context = undefined
  17. args = undefined
  18. }
  19. }
  20. }
  21. }
  22. function debounced() {
  23. context = this
  24. args = arguments
  25. timestamp = +(new Date())
  26. const callNow = immediate && !timeout
  27. if (!timeout) {
  28. timeout = setTimeout(later, wait)
  29. }
  30. if (callNow) {
  31. result = func.apply(context, args)
  32. context = undefined
  33. args = undefined
  34. }
  35. return result
  36. }
  37. function cancel() {
  38. if (timeout !== undefined) {
  39. clearTimeout(timeout)
  40. timeout = undefined
  41. }
  42. context = undefined
  43. args = undefined
  44. }
  45. debounced.cancel = cancel
  46. return debounced
  47. }