debounce.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 timeout = 0
  14. var isLeading = typeof options === 'boolean'
  15. var optLeading = 'leading' in opts ? opts.leading : isLeading
  16. var optTrailing = 'trailing' in opts ? opts.trailing : !isLeading
  17. var runFn = function () {
  18. runFlag = true
  19. timeout = 0
  20. callback.apply(context, args)
  21. }
  22. var endFn = function () {
  23. if (optLeading === true) {
  24. timeout = 0
  25. }
  26. if (!runFlag && optTrailing === true) {
  27. runFn()
  28. }
  29. }
  30. var cancelFn = function () {
  31. var rest = timeout !== 0
  32. clearTimeout(timeout)
  33. timeout = 0
  34. return rest
  35. }
  36. var debounced = function () {
  37. runFlag = false
  38. args = arguments
  39. context = this
  40. if (timeout === 0) {
  41. if (optLeading === true) {
  42. runFn()
  43. }
  44. } else {
  45. clearTimeout(timeout)
  46. }
  47. timeout = setTimeout(endFn, wait)
  48. }
  49. debounced.cancel = cancelFn
  50. return debounced
  51. }
  52. module.exports = debounce