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; position: fixed;
top: 0; top: 0;
left: 0; left: 0;
z-index: 400;
} }

View file

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