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/

Sam Deering
Meet the author
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

No Reader comments

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!