mirror of
https://github.com/nature-of-code/noc-book-2
synced 2024-11-17 07:49:05 +01:00
Merge pull request #408 from fturmel/PR/pause-examples-outside-viewport
Pause examples outside viewport (perf improvement)
This commit is contained in:
commit
bb9533434b
1 changed files with 22 additions and 0 deletions
|
@ -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"
|
||||
|
|
Loading…
Reference in a new issue