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

UseTimeout #506

Open
NickBolles opened this issue Aug 11, 2020 · 2 comments
Open

UseTimeout #506

NickBolles opened this issue Aug 11, 2020 · 2 comments

Comments

@NickBolles
Copy link

NickBolles commented Aug 11, 2020

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
Copy link
Owner

pikax commented Nov 1, 2020

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.

@jy0529
Copy link
Contributor

jy0529 commented Jan 23, 2021

Hi pikax, I love this repo and I want to participate this repo, so I add a new composable useTimeout, do you have time to review my PR? @pikax

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants