Skip to main content

useTimeoutFn

Wrapper for setTimeout with controls

Usage

Live Editor
function Demo() {
  const [text, setText] = useState("Please wait for 3 seconds");
  const [isPending, start] = useTimeoutFn(
    () => {
      setText("Fired!");
    },
    3000,
    { immediate: false },
  );

  return (
    <div>
      <p>{text}</p>
      <button
        onClick={() => {
          setText("Please wait for 3 seconds");
          start();
        }}
      >
        {isPending ? "Pending" : "Restart"}
      </button>
    </div>
  );
};

Result
Loading...

API

useTimeoutFn

Returns

Stoppable: A tuple with the following elements:

  • Whether to wait for the timer to execute.
  • Set timer.
  • Cancel timer.

Arguments

ArgumentDescriptionTypeDefaultValue
cbcallback(...args: unknown[]) => any (Required)-
intervalwait timenumber (Required)-
optionsoptional paramUseTimeoutFnOptions | undefined-

UseTimeoutFnOptions

PropertyDescriptionTypeDefaultValue
immediateStart the timer immediate after calling this functionbooleantrue