UseTimeout
NickBolles opened this issue · 2 comments
NickBolles commented
I recently had a use case for a timeout that I could cancel, or run early. Specifically in my app it's a "redirecting" page, where there's a timeout of 3 seconds and a button to do the redirect immediately.
First off, is this possible with cancellablePromise or one of the other composables?
If not, maybe this would be a good addition? Somethings I added to it are:
- SSR version for doing the timeout immediately on the server
- Completed and cancelled refs
- onUnmount cancel the timeout
Here's my implementation
import { ref, onBeforeUnmount } from "nuxt-composition-api";
export function useTimeout(ms: number | null, fn: () => void, opts: { enableSSRTimeout: boolean }) {
const timeoutHandle = ref<any | undefined>(undefined);
const cancelled = ref(false);
const complete = ref(false);
const timeoutMs = process.client || opts?.enableSSRTimeout ? ms : null;
/**
* cancel the timeout
* @returns whether the timeout was cancelled or not, if complete = true this will return false
*/
const cancelTimeout = (): boolean => {
if (complete.value === true) {
return false;
}
clearTimeout(timeoutHandle.value);
cancelled.value = true;
return true;
};
onBeforeUnmount(() => cancelTimeout());
const doTimeout = (): void => {
complete.value = true;
fn();
};
if (timeoutMs === null) {
doTimeout();
} else {
setTimeout(doTimeout, timeoutMs);
}
return {
timeoutHandle,
cancelled,
complete,
cancelTimeout
};
}
Edit: removed ssrTimeout in favor of useTimeout handling it itself
pikax commented
Thank you and sorry for taking so long, I was thinking in adding this, but I never got the time, if you don't mind in PR it, I will appreciated a lot.