Created
July 8, 2021 14:12
-
-
Save szxmsu/4066b6000386533eb981145e4e6de755 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const _ = (() => { | |
return { | |
debounce: function (func, wait, leading, trailing) { | |
wait = wait || 0; | |
leading = typeof leading === 'boolean' ? leading : true; | |
trailing = typeof trailing === 'boolean' ? trailing : false; | |
if (leading && trailing) { | |
throw new Error(); | |
} | |
let timeoutID; | |
return function () { | |
const object = this, args = arguments; | |
const delayed = function () { | |
if (trailing) { | |
func.apply(object, args); | |
} | |
timeoutID = undefined; | |
}; | |
if (timeoutID) { | |
clearTimeout(timeoutID); | |
} else if (leading) { | |
func.apply(object, args); | |
} | |
timeoutID = setTimeout(delayed, wait); | |
}; | |
}, | |
throttle: function (func, wait, leading, trailing) { | |
wait = wait || 0; | |
leading = typeof leading === 'boolean' ? leading : true; | |
trailing = typeof trailing === 'boolean' ? trailing : false; | |
if (leading && trailing) { | |
throw new Error(); | |
} | |
let timeoutID; | |
return function () { | |
const object = this, args = arguments; | |
const delayed = function () { | |
if (trailing) { | |
func.apply(object, args); | |
} | |
timeoutID = undefined; | |
}; | |
if (timeoutID === undefined) { | |
if (leading) { | |
func.apply(object, args); | |
} | |
timeoutID = setTimeout(delayed, wait); | |
} | |
}; | |
}, | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment