Skip to content

Instantly share code, notes, and snippets.

@andregoncalves
Created March 25, 2018 10:52
Show Gist options
  • Save andregoncalves/4e55c9c36a7dec03abf838c23a96f4ef to your computer and use it in GitHub Desktop.
Save andregoncalves/4e55c9c36a7dec03abf838c23a96f4ef to your computer and use it in GitHub Desktop.
[Throttling and debouncing] #js
// Throttling
// ES6 code
function throttled(delay, fn) {
let lastCall = 0;
return function (...args) {
const now = (new Date).getTime();
if (now - lastCall < delay) {
return;
}
lastCall = now;
return fn(...args);
}
}
// Using it
// Accepting the event only once every 200ms
const myHandler = (event) => // do something with the event
const tHandler = throttled(200, myHandler); // delay is 200ms
domNode.addEventListener("mousemove", tHandler);
// Debouncing
// ES6
function debounced(delay, fn) {
let timerId;
return function (...args) {
if (timerId) {
clearTimeout(timerId);
}
timerId = setTimeout(() => {
fn(...args);
timerId = null;
}, delay);
}
}
const myHandler = (event) => // do something with the event
const dHandler = debounced(200, myHandler);
domNode.addEventListener("input", dHandler);
/*
As the user types, the input event will get ignored until the user
stops typing for 200 ms. When 200 ms since the last keystroke
(or some other input action) elapses, the event listener will finally be triggered.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment