Created
January 11, 2017 18:31
-
-
Save Krabaton/42ca83f7b475880b847049800154fadf to your computer and use it in GitHub Desktop.
Debouncing
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
// 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); | |
} | |
} |
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
// 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