February 17, 2017

Zeno's Paradox of Infinite Loop Scrolling

or Everything Moves but You

My current project has a strange requirement. Given a collection of items, a user should be able to infinitely loop scroll left and right in a carousel. From strictly a UI perspective, this makes sense, when I move to the left, add items to the right and vice versa. From a developer's perspective, this is kind of crazy.

Let's assume I have a collection, we can use an array of numbers for this example:

const collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's assume I can only see five of these items on the screen at once. Thus, when we reach either "edge" of the array, we should get the items on the other "edge" to populate our visible five. For example, if I went past the left edge, I would see this: 9,10,1,2,3.

The way this is handled, from a developer's perspective, is that when you scroll the container you add and remove items simultaneously (or .map() a new set of items for better performance) so that the number of items is always the same. Because the number of items is a constant, when we "move" our items, we must compensate the scroll position of the container an equal amount. If you move to reveal an item on the left we must:

  1. Remove the item on the right 2) Add an item on the left 3) Then compensate the scroll position the width of one item

Doing this results in your scroll position being exactly the same as it was. Assuming a world where the wrapping container never changes width, and the performance of the machine you view this UI on is perfect, you would literally never move position. Crazy!

Similar to Zeno's paradox where the arrow never reaches its target, the user never actually scrolls despite what appears like scrolling.

JavaScriptWeb Development


Liked the post? Why not show it?! Stroke Kyle's ego by stroking clicking his beard. You can click up to 50 times if you really liked it.

Spot a typo? Submit a PR with the fix! This entire blog is open sourced at https://github.com/kyleshevlin/blog
Newer Post: Renderless Components
Older Post: Head Scratcher #1
Kyle Shevlin's face, which is mostly a beard with eyes
Kyle Shevlin is a front end web developer and software engineer who specializes in JavaScript and React.