Skip to content

Instantly share code, notes, and snippets.

@freddi301
Created October 11, 2019 10:01
Show Gist options
  • Save freddi301/9183575ec36033552095723ce722b723 to your computer and use it in GitHub Desktop.
Save freddi301/9183575ec36033552095723ce722b723 to your computer and use it in GitHub Desktop.
useScheduledEffect #react #hook
import { useEffect, useRef } from "react";
type TimeoutCallback = (timestamp: number) => void;
export function useScheduledEffect(
callback: TimeoutCallback,
timestamp: number | null,
) {
const savedCallback = useRef<TimeoutCallback | null>(callback);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
if (timestamp == null) {
return;
}
const timeout = Math.max(0, timestamp - Date.now());
const id = setTimeout(() => {
if (savedCallback.current != null) {
savedCallback.current(Date.now());
}
}, timeout);
return () => clearTimeout(id);
}, [timestamp]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment