From 8c9d8fd71a1504e1afa793d8414281a82f513e2b Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 26 May 2015 22:49:32 -0500 Subject: [PATCH] Add Throttling A Function Call as a javascript til. --- README.md | 1 + javascript/throttling-a-function-call.md | 25 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 javascript/throttling-a-function-call.md diff --git a/README.md b/README.md index 9d8100d..498cb10 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,7 @@ smart people at [Hashrocket](http://hashrocket.com/). ## javascript - [Character Codes from Keyboard Listeners](javascript/character-codes-from-keyboard-listeners.md) +- [Throttling A Function Call](javascript/throttling-a-function-call.md) - [Truthiness of Integer Arrays](javascript/truthiness-of-integer-arrays.md) ### postgres diff --git a/javascript/throttling-a-function-call.md b/javascript/throttling-a-function-call.md new file mode 100644 index 0000000..12dfc89 --- /dev/null +++ b/javascript/throttling-a-function-call.md @@ -0,0 +1,25 @@ +# Throttling A Function Call + +Imagine you have a JavaScript function that makes a request to your server. +Perhaps it is sending user input from a `textarea` to be processed by the +server. You may want to wrap this function in a keyboard event listener so +that you are sure to react immediately to any user input. However, as the +user starts typing away into this text area you may find that way to many +requests are being fired off to the server. The request needs to be +*throttled*. + +You can roll your own approach to sufficiently intermittent server calls. +Though, it turns out that [underscore.js](http://underscorejs.org/) comes +with two functions out of the box for this kind of behavior. + +- [`throttle`](http://underscorejs.org/#throttle) will give you function + that wraps your function in a way that essentially rate-limits it. + +- [`debounce`](http://underscorejs.org/#debounce), on the other hand, will + give you a function that only calls your function once `N` milliseconds + has passed since it was last called. + +These are two subtly different approaches to making sure a function gets +call, just not too often. + +h/t [Jake Worth](https://twitter.com/jwworth)