Puppeteer: How can I ensure all screenshots are captured before closing the browser?

I need to take screenshots every 20 milliseconds while a Puppeteer page is open, but the screenshots are being generated too quickly, causing many to not be saved if the browser closes too soon. How can I ensure that all screenshots are completed before the browser shuts down? Here is an example code snippet I am currently using:

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://example.com');

    for (let i = 0; i < 100; i++) {
        await page.screenshot({ path: `screenshot${i}.png` });
        await new Promise(resolve => setTimeout(resolve, 20));
    }

    await browser.close();
})();

Maybe try checking for pending promises before closing. If you’re taking screenshots so fast, they might overlap, causing the browser to shut down before they’re done. You could use something like a flag or counter to confirm all screenshots are saved before executing await browser.close(). Worth a shot!

If managing pending promises is becoming cumbersome, consider increasing the delay time between screenshots. The 20ms interval might be too short for each screenshot to be fully processed, especially if there’s any network or CPU latency. Try increasing the interval slightly to see if it makes a difference. Alternatively, you can also use asynchronous functions to handle each screenshot independently, ensuring that each operation completes before proceeding to closing the browser, which will give all pending processes the needed time to finish.