Merge pull request #408 from fturmel/PR/pause-examples-outside-viewport

Pause examples outside viewport (perf improvement)
This commit is contained in:
Daniel Shiffman 2023-09-06 21:52:51 -04:00 committed by GitHub
commit bb9533434b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -93,6 +93,28 @@ const Example = (data) => {
return () => window.removeEventListener('resize', handleWindowResize);
}, []);
React.useEffect(() => {
// start and stop the p5 example loop based on visibility
const curr = ref.current;
if (!curr || !loaded || !isLooping) return;
const intersectionCallback = (entries) => {
const p5Window = curr.contentWindow;
const [entry] = entries;
entry.isIntersecting ? p5Window.loop() : p5Window.noLoop();
};
const observer = new IntersectionObserver(intersectionCallback, {
root: null,
rootMargin: '0px',
threshold: 0,
});
observer.observe(curr);
return () => observer.unobserve(curr);
}, [ref, isLooping, loaded]);
return (
<div
className="not-prose my-4 clear-both rounded overflow-hidden border bg-gray-100"