Debouncing & Throttling
Last active
September 1, 2020 22:17
-
-
Save GGrassiant/0b893e9a1a4d9349287799d8125e2604 to your computer and use it in GitHub Desktop.
Debouncing & Throttling
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, immediate) => { | |
let timeout; | |
return function executedFunction() { | |
const context = this; | |
const args = arguments; | |
const later = () => { | |
timeout = null; | |
if (!immediate) func.apply(context, args); | |
}; | |
const callNow = immediate && !timeout; | |
clearTimeout(timeout); | |
timeout = setTimeout(later, wait); | |
if (callNow) func.apply(context, args); | |
}; | |
}; | |
debounceBtn.addEventListener('click', debounce(function() { | |
console.info('Hey! It is', new Date().toUTCString()); | |
}, 3000)); |
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, limit) => { | |
let inThrottle | |
return function() { | |
const args = arguments | |
const context = this | |
if (!inThrottle) { | |
func.apply(context, args) | |
inThrottle = true | |
setTimeout(() => inThrottle = false, limit) | |
} | |
} | |
} | |
throttleBtn.addEventListener('click', throttle(function() { | |
return console.log('Hey! It is', new Date().toUTCString()); | |
}, 1000)); |
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, limit) => { | |
let lastFunc | |
let lastRan | |
return function() { | |
const context = this | |
const args = arguments | |
if (!lastRan) { | |
func.apply(context, args) | |
lastRan = Date.now() | |
} else { | |
clearTimeout(lastFunc) | |
lastFunc = setTimeout(function() { | |
if ((Date.now() - lastRan) >= limit) { | |
func.apply(context, args) | |
lastRan = Date.now() | |
} | |
}, limit - (Date.now() - lastRan)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment