UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

45 lines 1.23 kB
"use client"; import { useEffect } from "react"; import { useRefWithInit } from "./useRefWithInit.js"; const EMPTY = 0; class Timeout { constructor() { this.currentId = EMPTY; this.clear = () => { if (this.currentId !== EMPTY) { clearTimeout(this.currentId); this.currentId = EMPTY; } }; this.disposeEffect = () => { return this.clear; }; } static create() { return new Timeout(); } /** * Executes `fn` after `delay`, clearing any previously scheduled call. */ start(delay, fn) { this.clear(); this.currentId = setTimeout(() => { this.currentId = EMPTY; fn(); }, delay); /* Node.js types are enabled in development */ } isStarted() { return this.currentId !== EMPTY; } } /** * A `setTimeout` with automatic cleanup and guard. */ function useTimeout() { const timeout = useRefWithInit(Timeout.create).current; // eslint-disable-next-line react-hooks/exhaustive-deps useEffect(timeout.disposeEffect, []); return timeout; } export { Timeout, useTimeout }; //# sourceMappingURL=useTimeout.js.map