0
# Time & Async Utilities
1
2
Utilities for handling timeouts, intervals, debouncing, and throttling with reactive controls and Vue lifecycle integration.
3
4
## Capabilities
5
6
### useTimeout
7
8
Reactive timeout utility with controls.
9
10
```typescript { .api }
11
/**
12
* Reactive timeout
13
* @param interval - Timeout duration in milliseconds
14
* @param options - Timeout options
15
* @returns Timeout controls
16
*/
17
function useTimeout(interval: number, options?: UseTimeoutOptions): UseTimeoutReturn;
18
19
interface UseTimeoutOptions {
20
controls?: boolean;
21
immediate?: boolean;
22
}
23
24
interface UseTimeoutReturn extends Stoppable {
25
isPending: Ref<boolean>;
26
start: () => void;
27
stop: () => void;
28
}
29
```
30
31
**Usage Example:**
32
33
```typescript
34
import { useTimeout, ref } from "@vueuse/shared";
35
36
const message = ref('');
37
38
const { isPending, start, stop } = useTimeout(1000, {
39
controls: true,
40
immediate: false
41
});
42
43
// Start timeout manually
44
start();
45
46
// Check if timeout is pending
47
console.log(isPending.value); // true
48
49
// Cancel timeout
50
stop();
51
```
52
53
### useTimeoutFn
54
55
Wrapper for setTimeout with reactive controls.
56
57
```typescript { .api }
58
/**
59
* Wrapper for setTimeout with controls
60
* @param cb - Callback function to execute
61
* @param interval - Timeout duration (ref, getter, or number)
62
* @param options - Timeout function options
63
* @returns Timeout function controls
64
*/
65
function useTimeoutFn(
66
cb: Fn,
67
interval: MaybeRefOrGetter<number>,
68
options?: UseTimeoutFnOptions
69
): UseTimeoutFnReturn;
70
71
interface UseTimeoutFnOptions {
72
immediate?: boolean;
73
}
74
75
interface UseTimeoutFnReturn extends Stoppable {
76
isPending: Ref<boolean>;
77
start: (...args: unknown[]) => void;
78
stop: () => void;
79
}
80
```
81
82
**Usage Example:**
83
84
```typescript
85
import { useTimeoutFn } from "@vueuse/shared";
86
87
const { isPending, start, stop } = useTimeoutFn(
88
() => console.log('Timeout executed!'),
89
1000,
90
{ immediate: false }
91
);
92
93
// Start timeout
94
start();
95
96
// Check status
97
if (isPending.value) {
98
console.log('Timeout is running...');
99
}
100
101
// Cancel if needed
102
stop();
103
```
104
105
### useInterval
106
107
Reactive counter that increases every interval.
108
109
```typescript { .api }
110
/**
111
* Reactive counter increased every interval
112
* @param interval - Interval duration in milliseconds
113
* @param options - Interval options
114
* @returns Interval controls with counter
115
*/
116
function useInterval(interval?: number, options?: UseIntervalOptions): UseIntervalReturn;
117
118
interface UseIntervalOptions {
119
controls?: boolean;
120
immediate?: boolean;
121
immediateCallback?: boolean;
122
}
123
124
interface UseIntervalReturn extends Stoppable {
125
counter: Ref<number>;
126
isPaused: Ref<boolean>;
127
pause: () => void;
128
resume: () => void;
129
reset: () => void;
130
}
131
```
132
133
**Usage Example:**
134
135
```typescript
136
import { useInterval } from "@vueuse/shared";
137
138
const { counter, pause, resume, reset, stop } = useInterval(1000, {
139
controls: true,
140
immediate: true
141
});
142
143
// Counter increments every second
144
watchEffect(() => {
145
console.log('Counter:', counter.value);
146
});
147
148
// Control the interval
149
setTimeout(() => pause(), 5000); // Pause after 5 seconds
150
setTimeout(() => resume(), 8000); // Resume after 8 seconds
151
setTimeout(() => reset(), 10000); // Reset counter after 10 seconds
152
```
153
154
### useIntervalFn
155
156
Wrapper for setInterval with reactive controls.
157
158
```typescript { .api }
159
/**
160
* Wrapper for setInterval with controls
161
* @param cb - Callback function to execute
162
* @param interval - Interval duration (ref, getter, or number)
163
* @param options - Interval function options
164
* @returns Interval function controls
165
*/
166
function useIntervalFn(
167
cb: Fn,
168
interval?: MaybeRefOrGetter<number>,
169
options?: UseIntervalFnOptions
170
): UseIntervalFnReturn;
171
172
interface UseIntervalFnOptions {
173
immediate?: boolean;
174
immediateCallback?: boolean;
175
}
176
177
interface UseIntervalFnReturn extends Pausable {
178
stop: () => void;
179
}
180
```
181
182
**Usage Example:**
183
184
```typescript
185
import { useIntervalFn, ref } from "@vueuse/shared";
186
187
const count = ref(0);
188
189
const { pause, resume, isActive, stop } = useIntervalFn(
190
() => { count.value++; },
191
1000,
192
{ immediate: true, immediateCallback: false }
193
);
194
195
// Control execution
196
setTimeout(() => pause(), 5000); // Pause after 5 seconds
197
setTimeout(() => resume(), 8000); // Resume after 8 seconds
198
setTimeout(() => stop(), 12000); // Stop permanently after 12 seconds
199
```
200
201
### useDebounceFn
202
203
Debounce execution of a function.
204
205
```typescript { .api }
206
/**
207
* Debounce execution of a function
208
* @param fn - Function to debounce
209
* @param ms - Debounce delay (ref, getter, or number)
210
* @param options - Debounce options
211
* @returns Debounced function with controls
212
*/
213
function useDebounceFn<T extends FunctionArgs>(
214
fn: T,
215
ms?: MaybeRefOrGetter<number>,
216
options?: DebounceFilterOptions
217
): DebouncedFn<T>;
218
219
interface DebounceFilterOptions {
220
maxWait?: MaybeRefOrGetter<number>;
221
rejectOnCancel?: boolean;
222
}
223
224
interface DebouncedFn<T extends FunctionArgs> {
225
(...args: Parameters<T>): Promise<ReturnType<T>>;
226
cancel(): void;
227
flush(): Promise<ReturnType<T>>;
228
isPending(): boolean;
229
}
230
```
231
232
**Usage Example:**
233
234
```typescript
235
import { useDebounceFn, ref } from "@vueuse/shared";
236
237
const searchQuery = ref('');
238
const searchResults = ref([]);
239
240
const debouncedSearch = useDebounceFn(
241
async (query: string) => {
242
if (query) {
243
const results = await fetch(`/api/search?q=${query}`);
244
searchResults.value = await results.json();
245
}
246
},
247
500,
248
{ maxWait: 1000, rejectOnCancel: false }
249
);
250
251
// Usage
252
watch(searchQuery, (query) => {
253
debouncedSearch(query);
254
});
255
256
// Control debounced function
257
debouncedSearch.cancel(); // Cancel pending execution
258
debouncedSearch.flush(); // Execute immediately
259
console.log(debouncedSearch.isPending()); // Check if pending
260
```
261
262
### useThrottleFn
263
264
Throttle execution of a function.
265
266
```typescript { .api }
267
/**
268
* Throttle execution of a function
269
* @param fn - Function to throttle
270
* @param ms - Throttle delay (ref, getter, or number)
271
* @param trailing - Execute on trailing edge
272
* @param leading - Execute on leading edge
273
* @param rejectOnCancel - Reject promise when cancelled
274
* @returns Throttled function with controls
275
*/
276
function useThrottleFn<T extends FunctionArgs>(
277
fn: T,
278
ms?: MaybeRefOrGetter<number>,
279
trailing?: boolean,
280
leading?: boolean,
281
rejectOnCancel?: boolean
282
): ThrottledFn<T>;
283
284
interface ThrottledFn<T extends FunctionArgs> {
285
(...args: Parameters<T>): Promise<ReturnType<T>>;
286
cancel(): void;
287
flush(): Promise<ReturnType<T>>;
288
}
289
```
290
291
**Usage Example:**
292
293
```typescript
294
import { useThrottleFn } from "@vueuse/shared";
295
296
const saveData = useThrottleFn(
297
async (data: any) => {
298
await fetch('/api/save', {
299
method: 'POST',
300
body: JSON.stringify(data)
301
});
302
},
303
1000,
304
true, // trailing
305
true // leading
306
);
307
308
// Multiple calls within 1000ms will be throttled
309
saveData({ name: 'John' });
310
saveData({ name: 'Jane' }); // Will be throttled
311
saveData({ name: 'Bob' }); // Will be throttled
312
```
313
314
### useLastChanged
315
316
Records the timestamp of the last change.
317
318
```typescript { .api }
319
/**
320
* Records timestamp of the last change
321
* @param source - Watch source
322
* @param options - Watch options
323
* @returns Ref with last changed timestamp
324
*/
325
function useLastChanged(
326
source: WatchSource,
327
options?: WatchOptions
328
): Ref<number>;
329
```
330
331
**Usage Example:**
332
333
```typescript
334
import { useLastChanged, ref } from "@vueuse/shared";
335
336
const name = ref('John');
337
const lastChanged = useLastChanged(name);
338
339
console.log(lastChanged.value); // Initial timestamp
340
341
name.value = 'Jane';
342
console.log(lastChanged.value); // Updated timestamp
343
344
// Check how long ago it changed
345
const secondsAgo = (Date.now() - lastChanged.value) / 1000;
346
console.log(`Changed ${secondsAgo} seconds ago`);
347
```
348
349
### useDateFormat
350
351
Get formatted date according to string of tokens passed in.
352
353
```typescript { .api }
354
/**
355
* Get the formatted date according to the string of tokens passed in
356
* @param date - The date to format (Date, timestamp, or string)
357
* @param formatStr - The combination of tokens to format the date
358
* @param options - Format options
359
* @returns Computed ref with formatted date string
360
*/
361
function useDateFormat(
362
date: MaybeRefOrGetter<DateLike>,
363
formatStr?: MaybeRefOrGetter<string>,
364
options?: UseDateFormatOptions
365
): UseDateFormatReturn;
366
367
type DateLike = Date | number | string | undefined;
368
369
interface UseDateFormatOptions {
370
locales?: MaybeRefOrGetter<Intl.LocalesArgument>;
371
customMeridiem?: (hours: number, minutes: number, isLowercase?: boolean, hasPeriod?: boolean) => string;
372
}
373
374
type UseDateFormatReturn = ComputedRef<string>;
375
```
376
377
**Usage Example:**
378
379
```typescript
380
import { useDateFormat, ref } from "@vueuse/shared";
381
382
const date = ref(new Date());
383
384
// Basic formatting
385
const formatted = useDateFormat(date, 'YYYY-MM-DD HH:mm:ss');
386
console.log(formatted.value); // '2023-12-07 14:30:15'
387
388
// Custom format
389
const customFormat = useDateFormat(date, 'dddd, MMMM Do YYYY, h:mm:ss a');
390
console.log(customFormat.value); // 'Thursday, December 7th 2023, 2:30:15 pm'
391
392
// With locales
393
const localized = useDateFormat(date, 'MMMM', {
394
locales: 'fr-FR'
395
});
396
console.log(localized.value); // 'décembre'
397
398
// Reactive date
399
const timestamp = ref(Date.now());
400
const reactiveFormat = useDateFormat(timestamp, 'MM/DD/YYYY');
401
402
// Format tokens: YYYY, MM, DD, HH, mm, ss, SSS, A/a (AM/PM), etc.
403
```