debounce.js 986 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. export default function debounce(func, wait, immediate) {
  2. let timeout
  3. let args
  4. let context
  5. let timestamp
  6. let result
  7. const later = function later() {
  8. const last = +(new Date()) - timestamp
  9. if (last < wait && last >= 0) {
  10. timeout = setTimeout(later, wait - last)
  11. } else {
  12. timeout = null
  13. if (!immediate) {
  14. result = func.apply(context, args)
  15. if (!timeout) {
  16. context = null
  17. args = null
  18. }
  19. }
  20. }
  21. }
  22. return 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 = null
  33. args = null
  34. }
  35. return result
  36. }
  37. }