Skip to content

Commit

Permalink
Pause visualization when off-screen
Browse files Browse the repository at this point in the history
  • Loading branch information
delasy committed Oct 18, 2024
1 parent f6a0495 commit c8a9049
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion components/Visualizer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@ export function Visualizer({
const interval = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const timeout = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const ref = React.useRef<HTMLDivElement | null>(null);
const paused = React.useRef(false);
const [running, setRunning] = React.useState(false);
const [startedAt, setStartedAt] = React.useState(Date.now());
const [, setRenderedAt] = React.useState(Date.now());

function stepSimulation() {
if (simulator.current === null) {
if (simulator.current === null && !paused.current) {
return;
}

Expand Down Expand Up @@ -66,6 +67,25 @@ export function Visualizer({
interval.current = setInterval(stepSimulation, REPLAY_SPEED);
}

function handleObserving([entry]: IntersectionObserverEntry[]) {
paused.current = !entry.isIntersecting;
}

React.useEffect(() => {
if (ref.current === null) {
return;
}

const observer = new IntersectionObserver(handleObserving);
observer.observe(ref.current);

return () => {
if (ref.current) {
observer.unobserve(ref.current);
}
};
}, [ref]);

React.useEffect(() => {
if (autoStart) {
startSimulation();
Expand Down

0 comments on commit c8a9049

Please sign in to comment.