Skip to content

Instantly share code, notes, and snippets.

@zachstronaut
Last active August 29, 2015 13:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zachstronaut/8721419 to your computer and use it in GitHub Desktop.
Save zachstronaut/8721419 to your computer and use it in GitHub Desktop.
/*
Ok, so let's say you've got a situation where one browser fires
two events and the other browser only fires one.
How about a specific example: IE does not fire the "change" event on
a text input when you press the enter key, whereas other browsers do.
Well, what if you want to execute some code both when an
input changes OR when a user presses enter? You don't want
your code to fire twice, but one browser sends two events!
DEBOUNCE to the rescue!
*/
// Using underscore.js debounce...
var exampleFn = _.debounce(function () {
// this code will only execute once
}, 1);
el.addEventListener('change', exampleFn);
el.addEventListener('keydown', function (e) {
// only on Enter key
if (e.keyCode != 13) return;
exampleFn();
});
/*
Now it doesn't matter whether a browser fires one or both of the
events at the same time! Man... I think this pattern could solve
all sorts of headaches with browsers firing inconsistent DOM events.
And to think... I had only been using debounce for a single kind
of event which was firing many times in succession... like scroll.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment