mirror of
https://git.alemi.dev/guestbook.rs.git
synced 2024-12-19 02:54:52 +01:00
fix: make sure we don't fetch concurrently
This commit is contained in:
parent
319a7ab890
commit
6824526c27
1 changed files with 16 additions and 10 deletions
|
@ -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;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue