Created
April 23, 2018 09:40
-
-
Save santhosh17s/1ca798567642b65be9da6cbf7c7abf7d to your computer and use it in GitHub Desktop.
Throttling & debounce technique in JS
This file contains hidden or 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
// Referred in - https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf | |
// Start execute the function until, no more action request. Last requrest get performed. | |
// Use case - Auto Save, Submit, file send action | |
const debounce = (func, delay) => { | |
let inDebounce | |
return function() { | |
const context = this | |
const args = arguments | |
clearTimeout(inDebounce) | |
inDebounce = setTimeout(() => func.apply(context, args), delay) | |
} | |
} | |
// Execute the function after period of time. Use cases - resize window, scroll browse | |
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)) | |
} | |
} | |
} | |
let sendFunction = (x) => console.log('Sending Values....' + x); | |
let windowResize = () => console.log('window got resized'); | |
//Like file submittion action | |
let send = document.getElementById('send'); | |
send.addEventListener('click', debounce(function() {sendFunction(10);}, 1000)); | |
window.addEventListener('resize', throttle(windowResize, 1500)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment