How to throttle scroll events in AngularJS

If you watch the scroll event, you will probably find yourself handling far more events than you need. The scroll event fires really quickly, and that can be a problem on mobile devices.

The following Angular directive will call a specified scroll event every 250 milliseconds.

angular.module('hereApp.directive').directive('onScroll', function($timeout) {
    'use strict';

    return {
        scope: {
            onScroll: '&onScroll',
        },
        link: function(scope, element) {
            var scrollDelay = 250,
                scrollThrottleTimeout,
                throttled = false,
                scrollHandler = function() {
                    if (!throttled) {
                        scope.onScroll();
                        throttled = true;
                        scrollThrottleTimeout = $timeout(function(){
                            throttled = false;
                        }, scrollDelay);
                    }
                };

            element.on("scroll", scrollHandler);

            scope.$on('$destroy', function() {
                element.off('scroll', scrollHandler);
            });
        }
    };
});

The scrollable element should look like this:

<div on-scroll="myScrollEvent()"></div>

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax