From c656233a73a9fd5c61964c217ac2cb3d25d745cc Mon Sep 17 00:00:00 2001 From: Ben Olson Date: Fri, 6 Jun 2014 17:25:44 -0400 Subject: [PATCH] Better throttling function --- bower.json | 2 +- jquery-ui-scrollable.js | 47 +++++++++++++++++++++++++++++------------ package.json | 2 +- 3 files changed, 36 insertions(+), 15 deletions(-) diff --git a/bower.json b/bower.json index 032ea70..33aeacf 100644 --- a/bower.json +++ b/bower.json @@ -1,6 +1,6 @@ { "name": "jquery-ui-scrollable", - "version": "0.1.4", + "version": "0.1.5", "ignore": [ "bower_components", "node_modules", diff --git a/jquery-ui-scrollable.js b/jquery-ui-scrollable.js index c55c266..3683131 100644 --- a/jquery-ui-scrollable.js +++ b/jquery-ui-scrollable.js @@ -65,28 +65,49 @@ * End jQuery UI Position **/ + /** + * throttle from: + * http://remysharp.com/2010/07/21/throttling-function-calls/ + */ + function throttle(fn, threshhold, scope) { + threshhold || (threshhold = 250); + var last, + deferTimer; + return function () { + var context = scope || this; + + var now = +new Date, + args = arguments; + if (last && now < last + threshhold) { + // hold on to it + clearTimeout(deferTimer); + deferTimer = setTimeout(function () { + last = now; + fn.apply(context, args); + }, threshhold); + } else { + last = now; + fn.apply(context, args); + } + }; + } + function trackScrolling( scroller ) { var _waiter = null; - scroller.onscroll = function ( e ) { - - if ( !_waiter && !scroller.ignoreScrolling ) { + scroller.onscroll = throttle( function ( e ) { - _waiter = setTimeout(function () { + if ( !scroller.ignoreScrolling ) { - $.each(scroller.watch, function () { + $.each(scroller.watch, function () { - this._checkPositioning( e ); + this._checkPositioning( e ); - }); - - _waiter = null; - - }, $.osb.scrollable.CONFIG.throttler); + }); } - } + }, $.osb.scrollable.CONFIG.throttler ); //console.log( 'Start listening to scrolling' ); scroller.element.on('scroll.scrollable', scroller.onscroll); @@ -163,7 +184,7 @@ window.Scrollable = monitor; $.widget('osb.scrollable', { - version: "0.1.4", + version: "0.1.5", widgetEventPrefix: 'scroll', diff --git a/package.json b/package.json index f5e3fd8..3616322 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "jquery-ui-scrollable", "title": "jQuery UI Scrollable", "description": "Enables monitoring, querying, or changing the scroll position of an element relative to a scrolling container", - "version": "0.1.4", + "version": "0.1.5", "author": { "name": "Ben Olson", "url": "http://bseth99.github.com/"