In sync Playwright, time.sleep() stalls a CDP screencast because the sync API only reads and dispatches protocol events while your code is inside a Playwright call. During a plain sleep, your Page.screencastFrame handler never runs, so no frame gets acked, and Chromium stops sending frames. The fix is to wait with something that keeps the dispatcher pumping.

We hit this in our automated product-walkthrough recorder, which drives headless Chromium with sync Playwright and captures frames over CDP while an AI narration track plays. One scene had a 76-second stretch with no actions, because the narration was timed to the app's own live sequence. That one scene broke the recording in a way no standalone measurement could explain.

What did the failure actually look like?

Two identical takes of the same scene produced 154 captured frames instead of 480, and the demo app's scripted live sequence froze for more than 15 seconds mid-scene while the narration kept going. Measured on its own, outside the recorder, every timing was perfect. The drift showed up only in rendered takes, which made it look like a timing bug rather than a capture bug.

The scene showed a lead-management demo whose live sequence runs on chained setTimeout calls: new leads arrive, get scored, and change status. The narration describes each event as it happens. In the broken takes, the narration described a status change that, on screen, had not happened yet.

Earlier productions never hit this. Their action beats were dense enough that a click, hover, or page.evaluate came along every few seconds and pumped the connection without us realizing. This was the first scene with a long gap and nothing calling into Playwright.

Why does time.sleep stop Page.screencastFrame events in sync Playwright?

The sync API runs Playwright's async connection to its driver on the same thread as your code, and it processes incoming messages only while a sync Playwright call is blocking. A time.sleep() blocks the whole thread, so event callbacks queue up unhandled. Your screencast handler never sends Page.screencastFrameAck, and Chromium waits for that ack before sending another frame.

Playwright documents a version of this under "time.sleep() leads to outdated state": Playwright relies on async operations internally, and they can't be processed during time.sleep, so the docs tell you to use page.wait_for_timeout() instead. Most people meet this as stale page state in a test. With a CDP screencast, it becomes a capture pipeline that stops dead.

The other half is the protocol's flow control. A screencast frame must be acknowledged by the client before Chromium keeps streaming. Ack in the handler and the stream runs. Leave the handler unscheduled and the stream stalls on the first unacked frame.

How do you reproduce the screencast stall?

Start a screencast on a page that animates constantly, ack every frame in the handler, then wait 20 seconds using three different methods. On Playwright 1.62.0 (Python 3.12, headless Chromium 151, Linux), plain time.sleep captured 3 frames in 20 seconds. A 250 ms pumped sleep captured 239 frames. page.wait_for_timeout captured 1,200.

import time
from playwright.sync_api import sync_playwright

HTML = """<div id=b style='width:50px;height:50px;background:red'></div>
<script>
window.ticks = 0;
(function tick(){ window.ticks++; setTimeout(tick, 100); })();
let x = 0;
(function anim(){ x = (x + 5) % 500;
  document.getElementById('b').style.marginLeft = x + 'px';
  requestAnimationFrame(anim); })();
</script>"""

def run(mode, secs=20):
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        ctx = browser.new_context(viewport={"width": 1280, "height": 720})
        page = ctx.new_page()
        page.set_content(HTML)
        cdp = ctx.new_cdp_session(page)
        frames = [0]

        def on_frame(params):
            frames[0] += 1
            cdp.send("Page.screencastFrameAck", {"sessionId": params["sessionId"]})

        cdp.on("Page.screencastFrame", on_frame)
        cdp.send("Page.startScreencast", {"format": "jpeg", "everyNthFrame": 1})

        deadline = time.monotonic() + secs
        if mode == "sleep":
            time.sleep(secs)                      # handler never runs
        elif mode == "pump":
            while (left := deadline - time.monotonic()) > 0:
                time.sleep(min(0.25, left))
                page.evaluate("1")                # dispatches queued events
        elif mode == "wait_for_timeout":
            page.wait_for_timeout(secs * 1000)    # pumps for the whole wait

        print(mode, "frames:", frames[0])
        browser.close()

for m in ("sleep", "pump", "wait_for_timeout"):
    run(m)
Wait method (20 s)Frames captured
time.sleep(20)3
Pumped sleep (250 ms slices + page.evaluate("1"))239
page.wait_for_timeout(20000)1,200

The 3 frames are the ones that arrived before the sleep started. After that, the stream is parked on an unacked frame until the next Playwright call. Adding the anti-throttling launch flags changed none of these numbers. Throttling isn't the cause; the event pump is.

Why did the page's own setTimeout timeline freeze too?

In production, the stalled screencast did not stay a capture-only problem. With frames unacked, the renderer's frame pipeline backed up, and the app's chained setTimeout sequence fell more than 15 seconds behind wall-clock time. How much the timers slip depends on how heavy the page is. Our light repro page kept its timers on time, while a heavy one did not.

To test this, we rebuilt the repro to look more like production: 1920x1080 at device scale factor 2, PNG frames, and 400 animated, blurred, box-shadowed tiles. Over 30 seconds, a chained 100 ms setTimeout should tick about 300 times. It managed 169 under time.sleep, 178 under the pumped sleep, and 187 under wait_for_timeout. Plain sleep was the worst, but every method lost ticks.

That second finding matters as much as the first. A sequence built from chained relative setTimeout waits builds up every bit of lateness, so it drifts under load whatever the recorder does. We fixed this in the app itself: we rewrote the live sequence against absolute deadlines (fire at t0 + offset, not "100 ms after the last thing"). After that, events landed at the same wall-clock offsets in every take.

What is the fix for long waits in a sync Playwright recorder?

Replace every plain time.sleep in the recording loop with a wait that keeps calling into Playwright, and target an absolute monotonic deadline, not a duration. Our recorder sleeps in slices of 250 ms or less, with a no-op page.evaluate between slices. It also launches Chromium with the three background-throttling flags as extra protection.

def _pump_sleep(page, deadline: float) -> None:
    """Sleep until an absolute time.monotonic() deadline while keeping the
    sync Playwright connection pumped, so CDP screencast acks keep flowing."""
    while True:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            return
        time.sleep(min(0.25, remaining))
        try:
            page.evaluate("1")
        except Exception:
            pass

browser = p.chromium.launch(
    headless=True,
    args=[
        "--disable-background-timer-throttling",
        "--disable-backgrounding-occluded-windows",
        "--disable-renderer-backgrounding",
    ],
)

# in the action loop: wait for the next narration anchor
target = t0 + anchor_time + action.get("delay_s", 0.0)
if target > time.monotonic():
    _pump_sleep(page, target)

# and for the scene's tail
_pump_sleep(page, t0 + narration_duration + tail_seconds)

The absolute deadline matters as much as the pump. Every page.evaluate round trip adds a few milliseconds, and a loop of fixed-length sleeps turns that into seconds of drift over a long scene. Our action timeline is anchored to word-level narration timestamps, the approach we describe in how to sync AI voiceover, music, and video using word-level timestamps. On that timeline, a late action stays late, because the loop can only wait forward and never catch up.

The launch flags did not fix the stall in our repro, and we would not rely on them alone. We keep them because headless and occluded pages can have their timer budgets throttled. On the same lead-management demo, that throttling stretched a 60-second live sequence by 10–15 seconds before we added them.

Should you use page.wait_for_timeout instead of a pumped sleep in 2026?

For most code, yes. page.wait_for_timeout keeps the dispatcher running for the whole wait, so frames are acked the moment they arrive. In our light repro it captured five times as many frames as the 250 ms pump. Pass it the remaining time to an absolute deadline, max(0, deadline - time.monotonic()) * 1000, and you get both properties.

Our production recorder ships the sliced pump because that was the fix that turned the 154-frame take back into a 480-frame take. The recorder also drops oversampled frames to roughly 25 fps before writing PNGs, so the pump's lower frame cap never reached the final video. If we were writing the recorder from scratch today, we would use a deadline-aware wait_for_timeout first and keep the slice loop for cases where we want to do work between slices.

Whichever you pick, the rule is the same. In sync Playwright with any event-driven CDP work running (screencasts, page.on("request") logging, console capture), never block the thread outside a Playwright call for longer than you can tolerate events piling up.

How do you catch this class of bug before it ships?

Log captured frames per second of scene and compare takes. A sudden collapse like 154 vs 480 on the same scene is the giveaway. Then check the take, not the plan: pull frames at each expected app event and confirm the screen shows that state. Standalone timing tests won't catch it, because they don't run the screencast that causes the stall.

The frame-level check was what pinned it down for us. One frame showed a lead's score pill already rendered while its status chip had not flipped yet. That narrowed the stall to a window of a few seconds inside the 76-second gap. From there, finding the only stretch of the loop with no Playwright calls in it was quick.

Watch for it whenever a sync Playwright script mixes long passive waits with CDP event handlers. That covers screen recorders, network-traffic loggers, and any test that sleeps while it waits for an event callback to fire.

The same walkthrough pipeline's talking-head layer had its own silent failures, including one where RunPod InfiniteTalk ignores your size param when the reference image disagrees. The lesson is the same there: measure the output, because a clean exit code proves nothing.

Summary: why does time.sleep break CDP capture in sync Playwright?

Sync Playwright dispatches events only while you're inside one of its calls, so a long time.sleep leaves Page.screencastFrame unhandled and unacked, and Chromium stops streaming. On a heavy page, the stall reaches the app's own timers too. To fix it, wait with page.wait_for_timeout or a pumped sleep aimed at an absolute deadline, and pin app-side sequences to absolute times.