Skip to content

Instantly share code, notes, and snippets.

@Krabaton
Created January 11, 2017 18:31
Show Gist options
  • Save Krabaton/42ca83f7b475880b847049800154fadf to your computer and use it in GitHub Desktop.
Save Krabaton/42ca83f7b475880b847049800154fadf to your computer and use it in GitHub Desktop.
Debouncing
// debounce function that will wrap our event
function debounce(fn, delay) {
// maintain a timer
let timer = null;
// closure function that has access to timer
return function() {
// get the scope and parameters of the function
// via 'this' and 'arguments'
let context = this;
let args = arguments;
// if event is called, clear the timer and start over
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(context, args);
}, delay);
}
}
// function to be called when user scrolls
function foo() {
console.log('You are scrolling!');
}
// wrap our function in a debounce to fire once 2 seconds have gone by
let elem = document.getElementById('container');
elem.addEventListener('scroll', debounce(foo, 2000));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment