Skip to content

Instantly share code, notes, and snippets.

@wlkns
Created October 15, 2025 12:01
Show Gist options
  • Select an option

  • Save wlkns/b34a25dcdfe3d5bc08d6a127f037ff09 to your computer and use it in GitHub Desktop.

Select an option

Save wlkns/b34a25dcdfe3d5bc08d6a127f037ff09 to your computer and use it in GitHub Desktop.
Scroll the browser window up and down at a configurable pixels per second.
/**
* Smoothly scrolls the entire page body from top to bottom
* at a specified rate in pixels per second.
*
* @param {number} ratePxPerSecond - The scroll speed in pixels per second (e.g., 100).
*/
function scrollDownAtRate(ratePxPerSecond) {
// Check for a valid rate
if (ratePxPerSecond <= 0) {
console.error("Scroll rate must be a positive number.");
return;
}
// Determine the maximum scroll position (the bottom of the page)
const targetScrollPosition = document.documentElement.scrollHeight - window.innerHeight;
// Check if the page is already at the bottom or if it's not scrollable
if (window.scrollY >= targetScrollPosition) {
console.log("Already at the bottom of the page.");
return;
}
let prevTimestamp = null;
/**
* The animation loop function, called by requestAnimationFrame.
* @param {number} timestamp - The time in milliseconds passed since the page loaded.
*/
function animateScroll(timestamp) {
if (!prevTimestamp) {
prevTimestamp = timestamp;
}
// Calculate the time elapsed (delta time) since the last frame in milliseconds
const deltaTime = timestamp - prevTimestamp;
// Calculate the distance to scroll in this frame:
// Distance = Rate (px/s) * Time (s)
const distanceThisFrame = ratePxPerSecond * (deltaTime / 1000);
// Update the previous timestamp for the next frame calculation
prevTimestamp = timestamp;
// Check if the calculated scroll will overshoot the target
const currentScroll = window.scrollY;
const remainingScroll = targetScrollPosition - currentScroll;
if (remainingScroll <= distanceThisFrame) {
// Scroll the remaining distance precisely to the bottom
window.scrollBy(0, remainingScroll);
console.log("Scroll to bottom complete.");
return; // Stop the animation loop
} else {
// Scroll the calculated distance
window.scrollBy(0, distanceThisFrame);
}
// Continue the animation loop
window.requestAnimationFrame(animateScroll);
}
// Start the animation loop
window.requestAnimationFrame(animateScroll);
}
// --- Example Usage ---
// Scroll the page at a rate of 100 pixels per second.
// The total time taken will depend on the height of the page.
// scrollDownAtRate(100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment