Skip to content

useInterval

Starts an interval when the component mounts, stops it when the component unmounts, and restarts it when the interval duration changes. Use it for polling, clocks, countdowns, or repeated UI updates.

Importing

ts
import { useInterval } from '@almighty-shogun/vue-utils'

Usage

ts
import { ref } from 'vue'
import { useInterval } from '@almighty-shogun/vue-utils'

const count = ref(0);
const interval = useInterval(1000, () => count.value++);

interval.stop();

Parameters

NameTypeDescription
msMaybeRef<number>Interval duration.
fnFunctionFunction called by the interval.

Returns

NameTypeDescription
start()() => voidStarts the interval when it is not already running.
stop()() => voidClears the active interval.

Type signature

ts
declare function useInterval(
    ms: MaybeRef<number>,
    fn: Function
): UseInterval;

type UseInterval = {
    start(): void;
    stop(): void;
};

All packages are released under the MIT License.