CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vueuse--shared

Collection of essential shared Vue Composition Utilities providing foundational building blocks for reactive Vue applications

Pending
Overview
Eval results
Files

time-async.mddocs/

Time & Async Utilities

Utilities for handling timeouts, intervals, debouncing, and throttling with reactive controls and Vue lifecycle integration.

Capabilities

useTimeout

Reactive timeout utility with controls.

/**
 * Reactive timeout
 * @param interval - Timeout duration in milliseconds
 * @param options - Timeout options
 * @returns Timeout controls
 */
function useTimeout(interval: number, options?: UseTimeoutOptions): UseTimeoutReturn;

interface UseTimeoutOptions {
  controls?: boolean;
  immediate?: boolean;
}

interface UseTimeoutReturn extends Stoppable {
  isPending: Ref<boolean>;
  start: () => void;
  stop: () => void;
}

Usage Example:

import { useTimeout, ref } from "@vueuse/shared";

const message = ref('');

const { isPending, start, stop } = useTimeout(1000, { 
  controls: true,
  immediate: false 
});

// Start timeout manually
start();

// Check if timeout is pending
console.log(isPending.value); // true

// Cancel timeout
stop();

useTimeoutFn

Wrapper for setTimeout with reactive controls.

/**
 * Wrapper for setTimeout with controls
 * @param cb - Callback function to execute
 * @param interval - Timeout duration (ref, getter, or number)
 * @param options - Timeout function options
 * @returns Timeout function controls
 */
function useTimeoutFn(
  cb: Fn, 
  interval: MaybeRefOrGetter<number>, 
  options?: UseTimeoutFnOptions
): UseTimeoutFnReturn;

interface UseTimeoutFnOptions {
  immediate?: boolean;
}

interface UseTimeoutFnReturn extends Stoppable {
  isPending: Ref<boolean>;
  start: (...args: unknown[]) => void;
  stop: () => void;
}

Usage Example:

import { useTimeoutFn } from "@vueuse/shared";

const { isPending, start, stop } = useTimeoutFn(
  () => console.log('Timeout executed!'),
  1000,
  { immediate: false }
);

// Start timeout
start();

// Check status
if (isPending.value) {
  console.log('Timeout is running...');
}

// Cancel if needed
stop();

useInterval

Reactive counter that increases every interval.

/**
 * Reactive counter increased every interval
 * @param interval - Interval duration in milliseconds
 * @param options - Interval options
 * @returns Interval controls with counter
 */
function useInterval(interval?: number, options?: UseIntervalOptions): UseIntervalReturn;

interface UseIntervalOptions {
  controls?: boolean;
  immediate?: boolean;
  immediateCallback?: boolean;
}

interface UseIntervalReturn extends Stoppable {
  counter: Ref<number>;
  isPaused: Ref<boolean>;
  pause: () => void;
  resume: () => void;
  reset: () => void;
}

Usage Example:

import { useInterval } from "@vueuse/shared";

const { counter, pause, resume, reset, stop } = useInterval(1000, {
  controls: true,
  immediate: true
});

// Counter increments every second
watchEffect(() => {
  console.log('Counter:', counter.value);
});

// Control the interval
setTimeout(() => pause(), 5000);   // Pause after 5 seconds
setTimeout(() => resume(), 8000);  // Resume after 8 seconds
setTimeout(() => reset(), 10000);  // Reset counter after 10 seconds

useIntervalFn

Wrapper for setInterval with reactive controls.

/**
 * Wrapper for setInterval with controls
 * @param cb - Callback function to execute
 * @param interval - Interval duration (ref, getter, or number)
 * @param options - Interval function options
 * @returns Interval function controls
 */
function useIntervalFn(
  cb: Fn, 
  interval?: MaybeRefOrGetter<number>, 
  options?: UseIntervalFnOptions
): UseIntervalFnReturn;

interface UseIntervalFnOptions {
  immediate?: boolean;
  immediateCallback?: boolean;
}

interface UseIntervalFnReturn extends Pausable {
  stop: () => void;
}

Usage Example:

import { useIntervalFn, ref } from "@vueuse/shared";

const count = ref(0);

const { pause, resume, isActive, stop } = useIntervalFn(
  () => { count.value++; },
  1000,
  { immediate: true, immediateCallback: false }
);

// Control execution
setTimeout(() => pause(), 5000);  // Pause after 5 seconds
setTimeout(() => resume(), 8000); // Resume after 8 seconds
setTimeout(() => stop(), 12000);  // Stop permanently after 12 seconds

useDebounceFn

Debounce execution of a function.

/**
 * Debounce execution of a function
 * @param fn - Function to debounce
 * @param ms - Debounce delay (ref, getter, or number)
 * @param options - Debounce options
 * @returns Debounced function with controls
 */
function useDebounceFn<T extends FunctionArgs>(
  fn: T, 
  ms?: MaybeRefOrGetter<number>, 
  options?: DebounceFilterOptions
): DebouncedFn<T>;

interface DebounceFilterOptions {
  maxWait?: MaybeRefOrGetter<number>;
  rejectOnCancel?: boolean;
}

interface DebouncedFn<T extends FunctionArgs> {
  (...args: Parameters<T>): Promise<ReturnType<T>>;
  cancel(): void;
  flush(): Promise<ReturnType<T>>;
  isPending(): boolean;
}

Usage Example:

import { useDebounceFn, ref } from "@vueuse/shared";

const searchQuery = ref('');
const searchResults = ref([]);

const debouncedSearch = useDebounceFn(
  async (query: string) => {
    if (query) {
      const results = await fetch(`/api/search?q=${query}`);
      searchResults.value = await results.json();
    }
  },
  500,
  { maxWait: 1000, rejectOnCancel: false }
);

// Usage
watch(searchQuery, (query) => {
  debouncedSearch(query);
});

// Control debounced function
debouncedSearch.cancel(); // Cancel pending execution
debouncedSearch.flush();  // Execute immediately
console.log(debouncedSearch.isPending()); // Check if pending

useThrottleFn

Throttle execution of a function.

/**
 * Throttle execution of a function
 * @param fn - Function to throttle
 * @param ms - Throttle delay (ref, getter, or number)
 * @param trailing - Execute on trailing edge
 * @param leading - Execute on leading edge
 * @param rejectOnCancel - Reject promise when cancelled
 * @returns Throttled function with controls
 */
function useThrottleFn<T extends FunctionArgs>(
  fn: T, 
  ms?: MaybeRefOrGetter<number>, 
  trailing?: boolean, 
  leading?: boolean, 
  rejectOnCancel?: boolean
): ThrottledFn<T>;

interface ThrottledFn<T extends FunctionArgs> {
  (...args: Parameters<T>): Promise<ReturnType<T>>;
  cancel(): void;
  flush(): Promise<ReturnType<T>>;
}

Usage Example:

import { useThrottleFn } from "@vueuse/shared";

const saveData = useThrottleFn(
  async (data: any) => {
    await fetch('/api/save', {
      method: 'POST',
      body: JSON.stringify(data)
    });
  },
  1000,
  true,  // trailing
  true   // leading
);

// Multiple calls within 1000ms will be throttled
saveData({ name: 'John' });
saveData({ name: 'Jane' }); // Will be throttled
saveData({ name: 'Bob' });  // Will be throttled

useLastChanged

Records the timestamp of the last change.

/**
 * Records timestamp of the last change
 * @param source - Watch source
 * @param options - Watch options
 * @returns Ref with last changed timestamp
 */
function useLastChanged(
  source: WatchSource, 
  options?: WatchOptions
): Ref<number>;

Usage Example:

import { useLastChanged, ref } from "@vueuse/shared";

const name = ref('John');
const lastChanged = useLastChanged(name);

console.log(lastChanged.value); // Initial timestamp

name.value = 'Jane';
console.log(lastChanged.value); // Updated timestamp

// Check how long ago it changed
const secondsAgo = (Date.now() - lastChanged.value) / 1000;
console.log(`Changed ${secondsAgo} seconds ago`);

useDateFormat

Get formatted date according to string of tokens passed in.

/**
 * Get the formatted date according to the string of tokens passed in
 * @param date - The date to format (Date, timestamp, or string)
 * @param formatStr - The combination of tokens to format the date
 * @param options - Format options
 * @returns Computed ref with formatted date string
 */
function useDateFormat(
  date: MaybeRefOrGetter<DateLike>, 
  formatStr?: MaybeRefOrGetter<string>, 
  options?: UseDateFormatOptions
): UseDateFormatReturn;

type DateLike = Date | number | string | undefined;

interface UseDateFormatOptions {
  locales?: MaybeRefOrGetter<Intl.LocalesArgument>;
  customMeridiem?: (hours: number, minutes: number, isLowercase?: boolean, hasPeriod?: boolean) => string;
}

type UseDateFormatReturn = ComputedRef<string>;

Usage Example:

import { useDateFormat, ref } from "@vueuse/shared";

const date = ref(new Date());

// Basic formatting
const formatted = useDateFormat(date, 'YYYY-MM-DD HH:mm:ss');
console.log(formatted.value); // '2023-12-07 14:30:15'

// Custom format
const customFormat = useDateFormat(date, 'dddd, MMMM Do YYYY, h:mm:ss a');
console.log(customFormat.value); // 'Thursday, December 7th 2023, 2:30:15 pm'

// With locales
const localized = useDateFormat(date, 'MMMM', { 
  locales: 'fr-FR' 
});
console.log(localized.value); // 'décembre'

// Reactive date
const timestamp = ref(Date.now());
const reactiveFormat = useDateFormat(timestamp, 'MM/DD/YYYY');

// Format tokens: YYYY, MM, DD, HH, mm, ss, SSS, A/a (AM/PM), etc.

Install with Tessl CLI

npx tessl i tessl/npm-vueuse--shared

docs

array-utilities.md

common-utilities.md

computed-utilities.md

index.md

reactivity.md

ref-utilities.md

state-management.md

time-async.md

utilities.md

watch-utilities.md

tile.json