smoother progress bar with requestAnimationFrame

This commit is contained in:
xenofem 2024-02-11 17:55:00 -05:00
parent 89093ac490
commit c25e539a0f
2 changed files with 35 additions and 24 deletions

View file

@ -120,4 +120,5 @@ html, body {
position: fixed;
top: 0;
left: 0;
z-index: 400;
}

View file

@ -1,4 +1,3 @@
const PROGRESS_UPDATE_INTERVAL = 50;
const PRELOAD_BACKWARD = 2;
const PRELOAD_FORWARD = 8;
@ -8,28 +7,37 @@ document.addEventListener('DOMContentLoaded', () => {
let currentPage = parseInt(localStorage.getItem(`${WORK_ID}-currentPage`)) || 0;
let duration = parseInt(localStorage.getItem(`${WORK_ID}-duration`)) || 10;
let paused = true;
let interval;
let elapsed = 0;
let rtl = (localStorage.getItem(`${WORK_ID}-rtl`) !== "false");
let paused = true;
function startTimer() {
if (interval) {
clearInterval(interval);
let elapsed = 0;
let timerLastRun = null;
let timerAnimationRequestID = null;
function requestTimer() {
timerAnimationRequestID = window.requestAnimationFrame(runTimer);
}
interval = setInterval(
function () {
function runTimer(now) {
if (paused) {
return;
}
elapsed += PROGRESS_UPDATE_INTERVAL;
if (timerLastRun === null) {
elapsed = 0;
} else {
elapsed += now - timerLastRun;
}
timerLastRun = now;
if (elapsed >= duration*1000) {
changePage(currentPage + 1);
elapsed = 0;
}
updateBar();
},
PROGRESS_UPDATE_INTERVAL,
);
requestTimer();
}
const progressBar = document.getElementById('progress');
@ -38,10 +46,11 @@ document.addEventListener('DOMContentLoaded', () => {
}
function stopTimer() {
if (interval) {
clearInterval(interval);
interval = null;
if (timerAnimationRequestID) {
window.cancelAnimationFrame(timerAnimationRequestID);
timerAnimationRequestID = null;
}
timerLastRun = null;
elapsed = 0;
updateBar();
}
@ -68,6 +77,7 @@ document.addEventListener('DOMContentLoaded', () => {
function changePage(pageNum) {
elapsed = 0;
updateBar();
const previous = IMAGES[currentPage];
const current = IMAGES[pageNum];
@ -98,7 +108,7 @@ document.addEventListener('DOMContentLoaded', () => {
stopTimer();
} else {
durationDisplay.style.textDecoration = "";
startTimer();
requestTimer();
}
}