JavaScript
Article

Touch Swipe Function Debounce Script

By Sam Deering

Speed is everything on touch devices. Calling a function when a touch swipe has completed instead of calling it multiple times… For example you may use it to update some navigation based on a finger swipe. FYI I’m using hammer.js to capture the touch events and underscore.js internal behavior to handle the debouncing.

// Create the listener function (debounce).
var updateCarouselNav = _.debounce(function(e) {

    console.log('checking nav....');

}, 500); // Maximum run of once per 500 milliseconds

//detect actions on carousel for update of navigation buttons
$("#carousel").on("release dragleft dragright swipeleft swiperight", function()
{
    updateCarouselNav();
});

Proof it works!

Before:

debounce-1

After:

debounce-2

Extra reading: http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

No Reader comments

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.