Skip to content

Commit

Permalink
clientside time prediction
Browse files Browse the repository at this point in the history
  • Loading branch information
alex-Arc committed Jan 8, 2025
1 parent b329ef0 commit a5f0749
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions apps/client/src/common/hooks/useClientTimePrediction.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { useEffect, useState } from 'react';
import { MaybeNumber, Playback } from 'ontime-types';

import { useTimer } from './useSocket';

const rate = 100;

export const useClientTimePrediction = () => {
const { current, playback } = useTimer();
const [clientCurrent, setClientCurrent] = useState<MaybeNumber>(null);
const [clientAdjust, setClientAdjust] = useState(0);

useEffect(() => {
let timeoutId: null | NodeJS.Timeout = null;
timeoutId = setInterval(() => {
setClientAdjust((val) => {
if (val < 1000) {
return val + rate;
}
return val;
});
}, rate);

return () => {
if (timeoutId) clearInterval(timeoutId);
};
}, []);

useEffect(() => {
setClientAdjust(0);
if (current === null) {
setClientCurrent(null);
}
}, [current]);

useEffect(() => {
if (playback === Playback.Pause) {
setClientCurrent(current);
} else if (current !== null) {
setClientCurrent(current - clientAdjust);
}
}, [clientAdjust, current, playback]);

return clientCurrent;
};

0 comments on commit a5f0749

Please sign in to comment.