I am processing unknown number of items in a loop. Processing each item takes variable time. As the overall operation is lengthy and to give the end user more control, I want to provide a pause button.
The items to process are provided by a third party generator function and I can't modify it. So total number of items is unknown.
Following is my attempt to implement the feature:
let processed = 0;
let paused = false;
let resume = () => {};
// a third party function, which I can't modify
async function* getItems() {
for (;;) yield 1;
}
// placeholder for a lengthy operation
async function process(item) {
return new Promise(resolve => setTimeout(resolve, 1000));
}
// is this a better way to implement pause?
async function enforcePause() {
if (paused)
return new Promise(resolve => {resume = resolve});
else return Promise.resolve();
}
btn.addEventListener('click', () => {
if (paused) {
resume();
paused = false;
btn.textContent = 'Pause';
} else {
paused = true;
btn.textContent = 'Resume';
}
});
// a lengthy operation
async function processAll() {
for await (let item of getItems()) {
await process(item);
counter.textContent = ++processed;
await enforcePause();
}
}
processAll();
<p>Progress: <span id="counter">0</span></p>
<button id="btn">Pause</button>
My queries are: