Skip to content

Instantly share code, notes, and snippets.

@btmills
Created January 20, 2016 22:58
Show Gist options
  • Save btmills/0d85d580b53cc1e02ec6 to your computer and use it in GitHub Desktop.
Save btmills/0d85d580b53cc1e02ec6 to your computer and use it in GitHub Desktop.
Throttle function
const Throttle = (delay = 30) => {
let timer = null;
let start = null;
return (cb) => {
if (start) {
const remaining = delay - (Date.now() - start);
clearTimeout(timer);
timer = setTimeout(() => {
cb();
timer = null;
start = Date.now();
}, remaining);
} else {
cb();
timer = setTimeout(() => {
timer = null;
start = null;
}, delay);
start = Date.now();
}
};
};
const throttle = new Throttle(1500);
window.onkeydown = (event) => throttle(() => console.log(event.keyCode));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment