JSFiddle - React, Tailwind, and code Playground
by ashish shubham
HTML
<div id="root" class="container">
</div>
CSS
.container {
height: 300px;
width: 80%;
border: 1px solid black;
overflow: auto;
}
.item {
width: 50px;
height: 50px;
background-color: #d3d3d8;
margin: 10px;
float: left;
}
JavaScript 1.7
function getContent(offset, num) {
let arr = [];
for (var i = offset; i < offset + num; i++) {
arr.push(i);
}
return new Promise((resolve) => {
setTimeout(() => {
resolve(arr);
}, Math.random() * 2000);
});
}
const container = document.getElementById('root');
async function* items(batchSize) {
let offset = 0;
while (true) {
yield await getContent(offset, batchSize);
offset += batchSize;
}
}
async function* events(name, condition) {
let resolve;
container.addEventListener(name, e => {
if (condition(e)) {
resolve(e);
}
});
while (true) {
yield await new Promise(_resolve => resolve = _resolve);
}
}
function append(items) {
let dom = items.map(item => `<div class=item>${item}</div>`).join('');
container.insertAdjacentHTML('beforeend', dom);
}
async function init() {
let eventIterator = events('scroll', () =>
container.scrollHeight === container.scrollTop + container.clientHeight);
for await (const page of items(50)) {
append(page);
await eventIterator.next();
}
}
init();