Skip to content

useTimeout

Category
Export Size
333 B
Last Changed
5 days ago

A reactive value that becomes true after a given time.

Demo

Usage

tsx
import { 
useTimeout
} from '@reause/shared'
const
ready
=
useTimeout
(1000)

After 1 second, ready becomes true.

With Controls

tsx
import { 
useTimeout
} from '@reause/shared'
const {
ready
,
start
,
stop
,
isPending
} =
useTimeout
(1000, {
controls
: true })
// Check if timeout is pending
console
.
log
(
isPending
) // true
// Stop the timeout
stop
()
// Start/restart the timeout
start
()

Options

OptionTypeDefaultDescription
controlsbooleanfalseExpose start, stop, and isPending controls
immediatebooleantrueStart the timeout immediately
callback() => voidCalled when the timeout completes

Callback on Timeout

tsx
import { 
useTimeout
} from '@reause/shared'
useTimeout
(1000, {
callback
: () => {
console
.
log
('Timeout completed!')
}, })

Reactive Interval

The timeout duration can be reactive:

tsx
import { 
useTimeout
} from '@reause/shared'
import {
useRef
} from 'react'
const
duration
=
useRef
(1000)
const
ready
=
useTimeout
(
duration
)
// Change the duration (only affects future timeouts when using controls)
duration
.
current
= 2000

Type Declarations

ts
export interface UseTimeoutOptions<Controls extends boolean = false> {
    controls?: Controls;
    callback?: () => void;
    immediate?: boolean;
    immediateCallback?: boolean;
}

export interface UseTimeoutReturn {
    ready: boolean;
    isPending: boolean;
    start: () => void;
    stop: () => void;
}

export function useTimeout(interval?: number, options?: UseTimeoutOptions<false>): boolean

export function useTimeout(interval: number, options: UseTimeoutOptions<true>): UseTimeoutReturn

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
93a98 - fix(shared): resolve useTimeout audit findings (#749)
8fddc - chore!: remove all Vue-only Maybe* types and getter unions, adopt React Ref (#462)

Released under the MIT License. v0.1.8