throttle.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * 节流函数;当被调用 n 毫秒后才会执行,如果在这时间内又被调用则至少每隔 n 秒毫秒调用一次该函数
  3. *
  4. * @param {Function} callback 回调
  5. * @param {Number} wait 多少秒毫
  6. * @param {Object} options 参数{leading: 是否在之前执行, trailing: 是否在之后执行}
  7. * @return {Function}
  8. */
  9. function throttle (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 optLeading = 'leading' in opts ? opts.leading : true
  16. var optTrailing = 'trailing' in opts ? opts.trailing : false
  17. var runFn = function () {
  18. if (!isDestroy) {
  19. runFlag = true
  20. callback.apply(context, args)
  21. timeout = setTimeout(endFn, wait)
  22. }
  23. }
  24. var endFn = function () {
  25. timeout = 0
  26. if (!isDestroy && !runFlag && optTrailing === true) {
  27. runFn()
  28. }
  29. }
  30. var cancelFn = function () {
  31. var rest = timeout !== 0
  32. clearTimeout(timeout)
  33. args = null
  34. context = null
  35. runFlag = false
  36. timeout = 0
  37. return rest
  38. }
  39. var throttled = function () {
  40. args = arguments
  41. context = this
  42. runFlag = false
  43. if (timeout === 0) {
  44. if (optLeading === true) {
  45. runFn()
  46. } else if (optTrailing === true) {
  47. timeout = setTimeout(endFn, wait)
  48. }
  49. }
  50. }
  51. throttled.cancel = cancelFn
  52. return throttled
  53. }
  54. module.exports = throttle