Debugging a Canvas hitch: the 100 ms freeze when a bead piece finishes ironing
On the 104×104 "Starry Night Town" pattern, the last bead melts and the screen freezes for about a tenth of a second. 0.7 seconds later the finish screen pops up and it freezes again. The fix for both hitches was committed at the end of October, and my last post left it at "more on that next time". I'm writing it up now because, after measuring it all again, I found that half the reasoning in the code comments doesn't survive measurement.
If you've built a Canvas game, or any page that's smooth almost all the time but hitches at one particular moment, here's what you can take away:
- A script. About thirty lines that zero in on one moment and work out how long the main thread stayed busy without a break.
- A rule of thumb. For a hitch like this, first move the work into idle time and slice it to fit the frame budget; only then consider a different drawing method. In this fix only the first half actually helped. The second half cost extra time.
- A checklist. Seven things to watch when measuring a one-off hitch, three of which I wrote down only after the numbers fooled me.
First, where it hitches.
Where it hitches: two stretches in the same second, about 100 ms each
I measured the versions before and after the fix (v1.8.11 and v1.8.12) side by side. In a headless browser I held the iron down and ironed this pattern, recording from just before it finished until after the finish screen appeared. Emulated tablet, CPU throttled 4x, 7 runs per version: 2 swept the board from start to finish, 5 took a shortcut. Whether the shortcut can be trusted, and why I drop the first run of every batch, each get a section later.
Every run of the old version had two stretches. The first, in the frame where finish() runs, was 74 to 100 ms; the second, after the finish screen appeared, was 95 to 111 ms. A frame's budget is 16.7 ms, so both blew through it by more than four times.
The browser's own trace shows who owns them. The first is a 104 ms task, almost entirely inside the game's frame callback. The second is a 100 ms task whose caller is listed as IntersectionObserver. Garbage collection added up to less than 10 ms across the surrounding four seconds, so it isn't involved.
Under the same conditions, the new version had 0 to 1 over-budget stretches per run, the longest 14 to 23 ms, and not a single dropped frame. The finish screen still appeared at the same time, around 718 ms.
So what are these two pieces of work, and why do they land in the same second?
Why the same second: a 700 ms gap
The first stretch. When the last bead melts, the game calls finish(). The old version switched the phase to "done" right there, and the bottom layer of the board had to be redrawn in full, because ironing lays a warm tint over it that has to come off once you're done. So in one frame, all 10,816 cells were redrawn in a single go.
The second stretch comes a little later. finish() sets a 700 ms timer, and only then does the finish screen appear. It shows a thumbnail of the finished piece: the whole piece is drawn into a 144×144-pixel canvas and then scaled up. The old version drew each bead as a rounded square with a radial gradient on top, all 10,816 of them. On that thumbnail, each bead is just 1.4 pixels across.
So that second looks like this: a big chunk of work at the start, 700 ms of almost nothing in the middle, and another big chunk at the end.
A quick note on who actually hits this. The game has a rule: on devices whose shorter screen edge is under 600 pixels, patterns larger than 32×32 count as "offline patterns" and can't be built on screen. So 104×104 only ever appears on tablets and computers. I ran both versions twice on a 32×32 pattern with a phone profile, and neither hitched; the longest stretch was 12 to 14 ms.
The fix is obvious once you read the code: move both chunks of work into the gap in the middle and cut them into small pieces. The hard part is proving it actually worked.
How to measure a hitch that happens only once
The repo already had a performance script that simulates real mouse and touch input and records frame intervals and long tasks. It had one limitation: it stopped recording as soon as it detected that ironing was done. The hitch happens in exactly the second after that.
So I wrote another one, with a recording window from 1.5 seconds before ironing finishes to 2.5 seconds after. The core is below, and it has nothing to do with this particular game:
// Zero in on one moment: record every frame's timestamp, wrap the functions you care about in timers,
// and work out how long the main thread stayed busy without a break.
function watchMoment() {
const frames = [], calls = [];
let on = false;
const tick = (t) => { if (on) frames.push(t); requestAnimationFrame(tick); };
requestAnimationFrame(tick);
const time = (name, fn) => function () {
if (!on) return fn.apply(this, arguments);
const t0 = performance.now();
try { return fn.apply(this, arguments); }
finally { calls.push([name, t0, performance.now() - t0]); }
};
return {
// Usage: watch.wrap(window, 'drawBoard')
wrap: (obj, name) => { obj[name] = time(name, obj[name]); },
start() { on = true; frames.length = 0; calls.length = 0; },
stop() {
on = false;
// Calls that run back to back (gaps under 2 ms) count as one stretch:
// a stretch is how long the main thread stayed busy without a break
const spans = [];
for (const [, t0, ms] of calls.slice().sort((a, b) => a[1] - b[1])) {
const last = spans[spans.length - 1];
if (last && t0 <= last.end + 2) last.end = Math.max(last.end, t0 + ms);
else spans.push({ start: t0, end: t0 + ms });
}
const held = spans.map((s) => s.end - s.start);
return {
maxHeld: Math.max(0, ...held), // longest stretch, ms
overBudget: held.filter((x) => x > 1000 / 60).length, // stretches over one frame's budget
// longest frame interval
maxFrame: Math.max(0, ...frames.slice(1).map((t, i) => t - frames[i])),
};
},
};
}
To use it, wrap the functions you care about, call start() before the moment and stop() after it. You get three numbers back: the longest stretch, the number of stretches over one frame's budget, and the longest frame interval.
You need all three, and two things have to be right before you even start measuring. This time I got fooled three times in a row, each more subtly than the last.
First, frame intervals fooled me. On an unthrottled desktop, the old version's work in the finish() frame took 19 to 23 ms, already over budget, yet the frame-interval log still ticked along at 16.7 ms with no dropped frames. That's because the frame callback's timestamp is the nominal frame time; once the work finishes, the next frame is scheduled as usual, just 2 to 6 ms late. Go by frame intervals alone and you'd conclude "fast machines are fine". In reality the old version had two over-budget stretches on every desktop run, the longest 23 to 30 ms. The script above shows the same thing on a test page: one 32 ms stretch, longest frame interval 16.8 ms.
Second, the first run fooled me. One run showed a 250 ms frame that never came back. Only the trace revealed that the game's own work in that frame was just 87 ms, while the browser's GPU process was busy for 238 ms at the same time, initializing its rendering context. My read is that this is a one-time cost the first time the browser takes that rendering path. So I drop the first run of every batch.
The third was the subtlest: script timers fooled me. I'll save that for the section on cost.
There's also a trade-off to own up to. Sweeping the whole 104×104 board with the iron takes 27 seconds, which is too slow to repeat every run under throttling. So I sweep for real for 2.5 seconds, then set the melt level straight to 89% and let the game's own auto-melt handle the rest. My assumption is that the work done at the moment ironing finishes doesn't depend on how you got there. I verified that with real sweeps only on the tablet profile, 3 runs per version, and the results matched the shortcut: old version, thumbnail 74 to 86 ms and board redraw 72 to 92 ms; new version, longest frame after finishing 16.8 ms. The two desktop profiles used the shortcut only and rely on that assumption. The shortcut leaves a mark, too: in the two throttled profiles, about half the runs had a 50 ms frame half a second before finishing, and none of the 6 real sweeps did. My guess is that setting the melt level causes it. It falls outside the second being measured.
With the measurement right, I can answer the question that matters most: is it fixed?
Is it fixed? Old versus new across three profiles after time slicing
Here are all three profiles. The tablet profile is the 7 runs above; the other two ran at least 5 times per version:
- Tablet, CPU throttled 4x. Old: 2 over-budget stretches per run, longest 95 to 111 ms. New: 0 to 1, longest 14 to 23 ms.
- Desktop, CPU throttled 4x. Old: 2 per run, longest 102 to 116 ms. New: 0 to 1, longest 16 to 18 ms.
- Desktop, unthrottled. Old: 2 per run, longest 23 to 30 ms. New: 0, longest 10 to 13 ms, though 5 of 16 runs dropped frames; more on that later.
The numbers show exactly how it was done. The board redraw is split into 5 to 6 chunks, a median of 33 ms in total with the longest chunk at a median of 7.4 ms; it's drawn off screen and swapped in, so the old image stays on screen meanwhile. The thumbnail is split into 12 to 15 chunks, one every 16 ms with at most 6 ms each, and is done within 500 ms. By the time the finish screen appears, the thumbnail is already drawn, so the step that used to take 74 to 86 ms now takes 0 to 1 ms.
Both kinds of slicing only kick in for large pieces: the thumbnail is pre-warmed when there are more than 2,500 cells, and the board is redrawn across frames when a side is longer than 48. Smaller pieces take the old path, which is the path I measured on the phone: a 32×32 piece never hitched, so it was left alone.
This way of splitting work by time budget is often called time slicing, and it's a general technique:
// Work to a time budget: spend at most budget ms this time and leave the rest for next time; return true when everything is done.
// You provide drawChunk(job, from, to): draw items from through to, at most 256 at a time.
function step(job, budget) {
const until = performance.now() + budget;
while (job.i < job.n) {
const end = Math.min(job.n, job.i + 256); // at most 256 per bite
drawChunk(job, job.i, end);
job.i = end;
if (performance.now() > until) break;
}
return job.i >= job.n;
}
// Use the 700 ms before the finish screen appears: do a slice every 16 ms, then hand over the result
function warm(job, done) {
const go = () => {
if (step(job, 6)) done(job); // at most 6 ms per slice, leaving room for the frame's own work
else setTimeout(go, 16);
};
setTimeout(go, 16);
}
Two details are worth copying. First, it only budgets 6 ms for itself, less than half a frame, because the game has its own work to do in that frame. Second, it processes at least 256 items before checking the clock, so the actual time spent runs a little over 6 ms, by at most one bite.
At this point, measured by how long the main thread stays busy without a break, the verdict is "fixed". I was ready to wrap up here, until I went to check another claim in the code comments.
The cost: 25–35% more main-thread work in that second
The comments say the thumbnail switched to sprites because "drawing a gradient for every bead is too slow". This time I measured that claim too.
First, the third time I got fooled. I timed a few key functions and added up their time in both versions from finish() to 300 ms after the finish screen appeared, taking the median across runs: 201 ms for the old version, 173 ms for the new one, so the new one looked 14% lighter. That number missed a big chunk. It didn't count the rest of the script in the frame callback, and script timers simply can't see the time the browser spends at the end of each frame processing draw commands and compositing the result. You need the browser's trace to count everything.
Here's the full count: how long the main thread was busy in the second after finish():
Old: 361 ms. New: 454 ms, 26% more. On the throttled desktop it was 350 versus 471, 35% more. Almost all of the extra went into the thumbnail, which grew from 139 ms to 237 ms.
Why would sprites be slower? I ran a separate controlled experiment: same page, same piece, same 144×144-pixel canvas:
The new version draws a small sprite for every color at every quarter-pixel offset, 496 in all, then stamps them on bead by bead. That's nearly 70% slower than per-bead gradients. Cut it to 21 sprites (one per color) and it beats gradients. So what's slow is probably not sprites as such, but switching the source canvas so often. Plain filled squares are the fastest at just 14 ms; compared with the gradient version, the channels differ by 9 on average (out of 255), and about 6% differ by more than 24. At this size the gradient is barely visible anyway, though I didn't do any subjective comparison of how alike they look.
So I tested it directly: turn off the "use sprites" switch in the new version, change nothing else, and measure again (tablet profile, 5 runs). It still didn't hitch, with 0 to 2 over-budget stretches per run and the longest at 15 to 20 ms. The thumbnail pre-warm (median across runs) dropped from 93 ms to 74 ms, and its longest chunk from 10.3 ms to 7.6 ms. Total main-thread busy time in that second was 367 ms, just 6 ms more than the old version.
So in this fix, the two halves did this. Slicing the work and moving it into the gap fixed the hitch at very little cost. Switching to sprites didn't help and cost about 90 ms extra. Within that extra, canvas processing at the end of the frame went from 14 ms to 86 ms, and commit from 27 ms to 56 ms. My guess is that the latter is because each of the 496 small canvases needs its own GPU resources, but I haven't verified it.
I haven't changed the code in the game repo; the live version still uses sprites. But the next time I face a trade-off like this, I'll measure the two halves separately.
One caveat to state clearly. My setup is headless Chrome 157 with a real GPU, unthrottled, this machine's M1 Max throughout; the 4x CPU throttling is only emulated. A real low-end tablet also has a slow GPU, so gradient fills would cost more than I measured, and both results could change. The conclusion holds on my setup; on another device, measure again.
The main problem is fixed and the cost is measured. Two things I still haven't figured out.
Two things still unsolved
The first: running right at the budget. Under 4x throttling, the new version still has 0 to 1 stretches per run over 16.7 ms, the longest 23 ms. They come in two kinds. One is the frame where finish() runs: finish() itself settles rewards, saves the game and plays a sound, which together take 7 to 10 ms, and adding the first redraw chunk tips it over. The other is a chunk colliding with work the frame was already doing; the 23 ms one is that kind. The first would need changes to what finish() itself does; for the second, lowering the per-chunk budget a bit should help. I haven't tried either.
The second: a few unexplained dropped frames. On the unthrottled desktop, 5 of the new version's 16 runs dropped frames after ironing finished: 4 dropped one frame, with a 33 ms gap before the next; 1 dropped two, with a 50 ms gap. In those runs, the longest main-thread stretch was only 10 to 11.5 ms. The old version's frame-interval log showed no dropped frames in 16 runs, but it had two over-budget frames every run, which, as covered above, frame-interval logs can't see. I went through the trace for one of those runs, and in those 33 ms no browser thread had a task longer than 2 ms. I haven't found the cause, so all I can do is note it here.
I don't have answers for either. What I can be sure of is the checklist below.
What to take with you: a checklist
Seven things for measuring a one-off hitch, every one of which I actually tripped over:
- Make the recording window cover what comes after the moment. Half of this hitch happened 0.7 seconds after the event, and the original script stopped right at the event.
- Look at frame intervals and unbroken busy time. Frame intervals only show dropped frames; work that runs past 16.7 ms without dropping a frame is invisible to them.
- Drop the first run of every batch. The first time a browser takes a rendering path there's often a one-time initialization cost. I learned this one from a fake 250 ms long frame.
- Use the trace to confirm who owns a long frame. Frame callbacks, timer callbacks and observer callbacks each show up clearly, and you can rule out garbage collection while you're at it.
- Measure each half of a change separately. Only one of the two halves helped this time, and measuring them together would never have shown it.
- Count total work from browser events, not just script time. Scripts can't see canvas processing and commit at the end of the frame.
- Be explicit about what the emulation can't do. CPU throttling doesn't slow the GPU; if you take a shortcut, run a few without it to compare.
The checklist covers the problems I already know about. Below are four I haven't figured out.
Four questions I haven't figured out
- Faster at which size? Sprites lose to gradients on a thumbnail where each bead is 1.4 pixels; what about larger images? The same function already uses gradients for the 512-pixel share card. Maybe no single drawing method should cover every size? Is there an optimization in your project that was only ever measured at one size?
- What counts as fixed? The longest stretch went from 100 ms to 23 ms, and the two hitches that hit every run are gone; what's left is a few stretches right at the budget and a few unexplained dropped frames. But total work in that second went up 26%: does that get paid back in battery? To avoid two hitches in one second, the CPU stays busy around 100 ms longer. How would you weigh that?
- A 33 to 50 ms gap where, in the run I checked, every thread was idle: how far should I chase it? It showed up in only 5 of 16 runs, and only on the fast machine. Is it the browser's scheduling, my measurement method, or something in the new code I haven't spotted?
- Why wasn't it measured at the time? The fix and the switch to sprites were the same commit. That commit carried no measurement of this part, and the repo's performance script stopped recording before the moment in question. Was the "too slow" in that comment measured, or estimated? The last time you wrote "changed to X because Y was slow", did you have numbers?
Is there a spot in your game or page that "just hitches at one moment"? If you measure it with the script above, I'd love to hear what you get, especially if it's different from what I found here.
— NiceDay