<input type="file" id="el">
<code id="out"></code>
const el = document.getElementById('el');
const out = document.getElementById('out');
el.addEventListener('change', async () => {
const file = el.files?.[0];
if (file) {
const reader = file.stream().getReader();
out.innerText = JSON.stringify({ fileSize: file.size });
let received = 0;
while (true) {
const chunk = await reader.read();
if (chunk.done) break;
// chunk.value.forEach((it) => it + 1);
received += chunk.value.byteLength;
out.innerText = JSON.stringify({
fileSize: file.size,
process: `${received} / ${file.size} (${((received / file.size) * 100).toFixed(2)}%)`,
});
}
}
});
The code above works well, <code>
will show progress in real-time.
But if I add the line chunk.value.forEach((it) => it + 1);
, the main thread seems to be blocked, the page stops responding until the file processing is completed. (Test in Edge 125)
I can use requestAnimationFrame
to fix it.
But why does it happen, is there a better way than requestAnimationFrame
?