Last active
June 1, 2020 15:13
-
-
Save sunderls/4c15060b664155297369855dd97a4d35 to your computer and use it in GitHub Desktop.
throttle/debounce in JavaScript
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 debounce = (func, wait, options = { | |
leading: false, | |
trailing: true | |
}) => { | |
// same timer for leading and trailing | |
let timer = null | |
// special flag to skip the trailing call if leading is true | |
let isCalledForLeading = false | |
return function () { | |
// when timer is up, trigger if trailing is true | |
const delayed = () => { | |
if (options.trailing && !isCalledForLeading) { | |
func.apply(this, arguments) | |
} | |
timer = null | |
} | |
// if no timer , then a instant trigger | |
if (options.leading && timer === null) { | |
func.apply(this, arguments) | |
isCalledForLeading = true | |
} else { | |
isCalledForLeading = false | |
} | |
// clear time and set a new one | |
window.clearTimeout(timer) | |
timer = setTimeout(delayed, wait) | |
} | |
} |
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 throttle = (func, wait, options = {leading: true, trailing: true}) => { | |
let timer = null | |
let lastContext = null | |
let lastArgs = null | |
return function(...args) { | |
// 1. if called within cool time, then store it for later call | |
if (timer !== null) { | |
lastContext = this | |
lastArgs = args | |
return | |
} | |
// 2. if other than cool time, execute it | |
if (options.leading !== false) { | |
func.call(this, ...args) | |
} else { | |
// save for trailing call if needed | |
lastContext = this | |
lastArgs = args | |
} | |
// 3. set a timeout to clear the cool, time | |
// and run the stored context | |
const timeup = () => { | |
if (options.trailing !== false && lastArgs !== null) { | |
func.call(lastContext, ...lastArgs) | |
lastContext = null | |
lastArgs = null | |
timer = setTimeout(timeup, wait) | |
} else { | |
timer = null | |
} | |
} | |
timer = setTimeout(timeup, wait) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment