debounce.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * 函数去抖;当被调用 n 毫秒后才会执行,如果在这时间内又被调用则将重新计算执行时间
  3. *
  4. * @param {Function} callback 回调
  5. * @param {Number} wait 多少秒毫
  6. * @param {Object} options 参数{leading: 是否在之前执行, trailing: 是否在之后执行}
  7. * @return {Function}
  8. */
  9. function debounce (callback, wait, options) {
  10. var args, context
  11. var opts = options || {}
  12. var runFlag = false
  13. var isDestroy = false
  14. var timeout = 0
  15. var isLeading = typeof options === 'boolean'
  16. var optLeading = 'leading' in opts ? opts.leading : isLeading
  17. var optTrailing = 'trailing' in opts ? opts.trailing : !isLeading
  18. var runFn = function () {
  19. if (!isDestroy) {
  20. runFlag = true
  21. timeout = 0
  22. callback.apply(context, args)
  23. }
  24. }
  25. var endFn = function () {
  26. if (optLeading === true) {
  27. timeout = 0
  28. }
  29. if (!isDestroy && !runFlag && optTrailing === true) {
  30. runFn()
  31. }
  32. }
  33. var cancelFn = function () {
  34. var rest = timeout !== 0
  35. clearTimeout(timeout)
  36. args = null
  37. context = null
  38. timeout = 0
  39. return rest
  40. }
  41. var debounced = function () {
  42. runFlag = false
  43. args = arguments
  44. context = this
  45. if (timeout === 0) {
  46. if (optLeading === true) {
  47. runFn()
  48. }
  49. } else {
  50. clearTimeout(timeout)
  51. }
  52. timeout = setTimeout(endFn, wait)
  53. }
  54. debounced.cancel = cancelFn
  55. return debounced
  56. }
  57. module.exports = debounce