let size = 1;
let arr = ["a", "b", "c", "d", "e"]
window.addEventListener("scroll", () => {
const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
if (clientHeight scrollTop >= scrollHeight - 1) {
size = 1;
console.log("adding");
}
});
let items = arr.slice(0, size);
console.log(items);
This is a dummy array just to showcase the problem. The items
array should receive more items from arr
array as the user reaches the end of the page.
How can I increase a copy of an array using the variable as an endpoint for an array? I'm trying to run this code above but the items
array is not being updated.
This dummy code is a pseudo example of infinite scrolling.
CodePudding user response:
The problem has nothing to do with slice
. The problem is that the console.log(items);
line runs only once and before the scroll event handler runs.
Here is a simpler example that demonstrates the issue. In this case setTimeout()
's handler takes the place of the scroll event handler.
let x = 1;
setTimeout(() => {
x = 2;
}, 0);
console.log(x); //logs 1 (not 2)