1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- function debounce (callback, wait, options) {
- var args, context
- var opts = options || {}
- var runFlag = false
- var timeout = 0
- var isLeading = typeof options === 'boolean'
- var optLeading = 'leading' in opts ? opts.leading : isLeading
- var optTrailing = 'trailing' in opts ? opts.trailing : !isLeading
- var runFn = function () {
- runFlag = true
- timeout = 0
- callback.apply(context, args)
- }
- var endFn = function () {
- if (optLeading === true) {
- timeout = 0
- }
- if (!runFlag && optTrailing === true) {
- runFn()
- }
- }
- var cancelFn = function () {
- var rest = timeout !== 0
- clearTimeout(timeout)
- timeout = 0
- return rest
- }
- var debounced = function () {
- runFlag = false
- args = arguments
- context = this
- if (timeout === 0) {
- if (optLeading === true) {
- runFn()
- }
- } else {
- clearTimeout(timeout)
- }
- timeout = setTimeout(endFn, wait)
- }
- debounced.cancel = cancelFn
- return debounced
- }
- module.exports = debounce
|