Smarter Javascript Callbacks

Posted on in javascript, webdev

Every Javascript developer has used callbacks, some love them, some hate them, but there’s no denial you’ll have to deal with callbacks if you touch Javascript code.

What not many people know for some reason is the concept of two nifty functions existant in libraries such as Underscore and LoDash, namely debounce and throttle.

The fist one is useful when you want to peform an action after an event has stopped happening, for example, a markdown preview tool might want to wait for 1 second after the user stopped typing in order to actually parse the text to markdown. debounce takes a function and returns a new function “which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked” — according to Underscore’s documentation.

If you don’t want to include a whole library just for this function, you can use this little gist, which is just an adaptation of Backbone’s debounce.

The second function I’d like to talk about is throttle, this guy takes a function as parameter and returns a new function that “when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds”. This is really usefor for events that happen too fast as we can limit how often we want to call it, for example resize and scroll events.

Again, if you don’t want to include a whole library, here’s a little adaptation of Backbone’s throttle.

Example Usage

Let’s see an example of how one of these functions would be used in regular jQuery javascript:

Conclusion

As you can see, it’s really easy to start using these functions, by using them you can most likely experience quite some gains in overall UI responsiveness of your app. They are a good tool in every frontend developer out there but remember, “When you have a hammer, everything looks like a nail”, even though it’s quite hard to misuse them, use them wisely.