Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix remaining time after change page visability #478

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ const Toast = (props: ToastProps) => {
() => toast.duration || durationFromToaster || TOAST_LIFETIME,
[toast.duration, durationFromToaster],
);
const remainingTime = React.useRef(duration);
const closeTimerStartTimeRef = React.useRef(0);
const offset = React.useRef(0);
const lastCloseTimerStartTimeRef = React.useRef(0);
Expand Down Expand Up @@ -161,15 +162,14 @@ const Toast = (props: ToastProps) => {
React.useEffect(() => {
if ((toast.promise && toastType === 'loading') || toast.duration === Infinity || toast.type === 'loading') return;
let timeoutId: NodeJS.Timeout;
let remainingTime = duration;

// Pause the timer on each hover
const pauseTimer = () => {
if (lastCloseTimerStartTimeRef.current < closeTimerStartTimeRef.current) {
// Get the elapsed time since the timer started
const elapsedTime = new Date().getTime() - closeTimerStartTimeRef.current;

remainingTime = remainingTime - elapsedTime;
remainingTime.current = remainingTime.current - elapsedTime;
}

lastCloseTimerStartTimeRef.current = new Date().getTime();
Expand All @@ -179,15 +179,15 @@ const Toast = (props: ToastProps) => {
// setTimeout(, Infinity) behaves as if the delay is 0.
// As a result, the toast would be closed immediately, giving the appearance that it was never rendered.
// See: https://github.com/denysdovhan/wtfjs?tab=readme-ov-file#an-infinite-timeout
if (remainingTime === Infinity) return;
if (remainingTime.current === Infinity) return;

closeTimerStartTimeRef.current = new Date().getTime();

// Let the toast know it has started
timeoutId = setTimeout(() => {
toast.onAutoClose?.(toast);
deleteToast();
}, remainingTime);
}, remainingTime.current);
};

if (expanded || interacting || (pauseWhenPageIsHidden && isDocumentHidden)) {
Expand Down