Yesterday afternoon a colleague hit a problem while building pages for a new project — one whose scaffolding I had set up. When collapsing or expanding the secondary menu, the ECharts charts in the main view rendered incorrectly: their widths no longer fit the container.
Analyzing the Problem
Hearing the description, my first instinct was to check whether his code called chartInstance.resize on the resize event — ECharts charts size themselves to their container, so whenever the page width changes you need to call chartInstance.resize to recompute the chart width.
He was calling it. Yet the charts didn’t budge. That made me wonder whether collapsing the secondary menu triggered a resize event at all — the overall page width hadn’t changed, only the sidebar’s — so I dispatched one manually with new Event('resize'):
const onChangeCollapse = () => { const resizeEvent = new Event('resize'); window.dispatchEvent(resizeEvent); // ... other logic};Now chartInstance.resize did fire on collapse, and the chart widths were recomputed — but they were still wrong. With the menu collapsed the chart rendered too narrow; with the menu expanded it rendered too wide, overflowing the screen. At first this was genuinely puzzling.


Then I moved the chartInstance.resize call into a setTimeout with a 1-second delay, and everything rendered correctly. That cleared up the mystery.
The broken rendering came from the container’s width not changing in real time — the change lags behind. Every chartInstance.resize call was therefore rendering against the previous width.
With the root cause in hand, the fix was straightforward: run chartInstance.resize in a setTimeout with a sensible delay. My collapse/expand animation lasts 0.3s, so passing 300 as the second argument to setTimeout resolved the issue.
The Cleaner Fix
While writing this up it occurred to me that the first approach means wrapping every single chartInstance.resize call in a timer — tedious, and if the animation duration ever changes you’d have to update it in every page. Better: put the manual resize dispatch itself inside the setTimeout. The animation has finished by then, so when the page receives the event, the container widths have already settled.
const DEALY = 0.3;const onChangeCollapse = () => { setTimeout(() => { const resizeEvent = new Event('resize'); window.dispatchEvent(resizeEvent); // ... other logic }, DEALY * 100);};