throttle the iframe preview so that it doesn't stop updating at the end of code generation due to too many updates
This commit is contained in:
parent
c4b99c125e
commit
99508d8e03
@ -1,13 +1,17 @@
|
|||||||
|
import useThrottle from "../hooks/useThrottle";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
code: string;
|
code: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function Preview({ code }: Props) {
|
function Preview({ code }: Props) {
|
||||||
|
const throttledCode = useThrottle(code, 200);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-[704px]">
|
<div className="w-[704px]">
|
||||||
<iframe
|
<iframe
|
||||||
title="Iframe Example"
|
title="Preview"
|
||||||
srcDoc={code}
|
srcDoc={throttledCode}
|
||||||
className="border-[4px] border-black rounded-[20px] shadow-lg
|
className="border-[4px] border-black rounded-[20px] shadow-lg
|
||||||
transform scale-[0.8] origin-top-left w-[1280px] h-[832px]"
|
transform scale-[0.8] origin-top-left w-[1280px] h-[832px]"
|
||||||
></iframe>
|
></iframe>
|
||||||
|
|||||||
28
frontend/src/hooks/useThrottle.ts
Normal file
28
frontend/src/hooks/useThrottle.ts
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
import React from "react";
|
||||||
|
|
||||||
|
// Updates take effect immediately if the last update was more than {interval} ago.
|
||||||
|
// Otherwise, updates are throttled to {interval}. The latest value is always sent.
|
||||||
|
// The last update always gets executed, with potentially a {interval} delay.
|
||||||
|
export function useThrottle(value: string, interval = 500) {
|
||||||
|
const [throttledValue, setThrottledValue] = React.useState(value);
|
||||||
|
const lastUpdated = React.useRef<number | null>(null);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
if (!lastUpdated.current || now >= lastUpdated.current + interval) {
|
||||||
|
lastUpdated.current = now;
|
||||||
|
setThrottledValue(value);
|
||||||
|
} else {
|
||||||
|
const id = window.setTimeout(() => {
|
||||||
|
lastUpdated.current = now;
|
||||||
|
setThrottledValue(value);
|
||||||
|
}, interval);
|
||||||
|
|
||||||
|
return () => window.clearTimeout(id);
|
||||||
|
}
|
||||||
|
}, [value, interval]);
|
||||||
|
|
||||||
|
return throttledValue;
|
||||||
|
}
|
||||||
|
export default useThrottle;
|
||||||
Loading…
Reference in New Issue
Block a user