fix: make sure we don't fetch concurrently

This commit is contained in:
əlemi 2024-01-04 04:34:46 +01:00
parent 319a7ab890
commit 6824526c27
Signed by: alemi
GPG key ID: A4895B84D311642C

View file

@ -44,6 +44,7 @@ export default function hookInfiniteScroll(builder, opt) {
let container = document.getElementById(container_id); let container = document.getElementById(container_id);
let last_activation = Date.now(); let last_activation = Date.now();
let currently_fetching = false;
let offset = 0; let offset = 0;
function scrollDepth() { function scrollDepth() {
@ -52,18 +53,23 @@ export default function hookInfiniteScroll(builder, opt) {
} }
let callback = async (ev) => { let callback = async (ev) => {
if (currently_fetching) return; // another callback is already active
if (ev !== true && scrollDepth() < threshold) return; // not scrolled enough if (ev !== true && scrollDepth() < threshold) return; // not scrolled enough
if (ev !== true && Date.now() - last_activation < debounce) return; // triggering too fast if (ev !== true && Date.now() - last_activation < debounce) return; // triggering too fast
last_activation = Date.now(); try {
let response = await fetch(`${api_url}?${offset_arg}=${offset}`); currently_fetching = true;
let replies = await response.json(); let response = await fetch(`${api_url}?${offset_arg}=${offset}`);
if (replies.length == 0) { let replies = await response.json();
// reached end, unregister self if (replies.length == 0) { // reached end, unregister self
return document.removeEventListener("scroll", callback); return document.removeEventListener("scroll", callback);
} }
offset += free_index ? replies.length : 1; // track how deep we went offset += free_index ? replies.length : 1; // track how deep we went
for (let repl of replies) { last_activation = Date.now();
container.innerHTML += builder(repl); for (let repl of replies) {
container.innerHTML += builder(repl);
}
} finally {
currently_fetching = false;
} }
}; };