February 17, 2017

Zeno's Paradox of Infinite Loop Scrolling

or Everything Moves but You
edit

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.


Liked the post?
Give the author a dopamine boost with a few "beard strokes". Click the beard up to 50 times to show your appreciation.
Want to read more?
Tags
Kyle Shevlin's face, which is mostly a beard with eyes

Kyle Shevlin is the founder & lead software engineer of Agathist, a software development firm with a mission to build good software with good people.

Logo for Data Structures and Algorithms
Data Structures and Algorithms
Check out my courses!
If you enjoy my posts, you might enjoy my courses, too. Click the button to view the course or go to Courses for more information.
Sign up for my newsletter
Let's chat some more about TypeScript, React, and frontend web development. Unsubscribe at any time.