views:

387

answers:

1

We have a UI widget on our main UI that uses JavaScript to respond to scrolling events from the browser. The response to each scroll event is relatively expensive. A user can easily "queue" up a large set of scrolling events, while the first several are being processed and rendering within the widget.

The problem with this is that then the widget ends up in "scroll processing purgatory", where each incremental intermediate scroll event is processed and rendered.

For example: User has scrolled from a-b, then b-c, then d-e, then e-f, and so on. The scroll event processing may still be working on rendering the b-c scroll by the time the user has triggered a y-z event.

What we'd like to do instead is have a more intelligent management of these events. It would be great if we could render the results of a scroll event, then "catch up" to wherever the user is, and skip any of the intermediate scrolls that are now outdated.

What's the best way to do this?

+1  A: 

You may already be doing something like this, but I would use a timer that would essentially judge whether or not the user is still actively scrolling.

Something akin to this:

// need to have this variable outside the scope of the handler defined below
var timeoutId = null;

// think of "connect" as pseudocode for whatever you use to connect handlers
connect(widget, "onscroll", function() {
    // ...scrolling...
    if(timeoutId != null) clearTimeout(timeoutId);
    timeoutId = setTimeout(function() {
        // *probably* done scrolling, it has been  
        // 1 second since the last scroll...  
        // run your code to render current position here  
    }, 1000);
});
Jason Bunting