Skip to content

Commit 4466058

Browse files
authored
feat(useNow): expose immediate option (#4768)
1 parent 39274b0 commit 4466058

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

packages/core/useNow/index.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,19 @@ describe('useNow', () => {
99
expect(+now.value).toBeLessThanOrEqual(+new Date())
1010
})
1111

12+
it('starts lazily if immediate is false', () => {
13+
const initial = +new Date()
14+
const { now, resume } = useNow({ controls: true, immediate: false })
15+
16+
expect(+now.value).toBe(initial)
17+
vi.advanceTimersByTime(50)
18+
expect(+now.value).toBe(initial)
19+
20+
resume()
21+
vi.advanceTimersByTime(50)
22+
expect(+now.value).toBeGreaterThan(initial)
23+
})
24+
1225
function testControl(interval: any) {
1326
it(`should control now timestamp by ${interval}`, async () => {
1427
let initial = +new Date()

packages/core/useNow/index.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,13 @@ export interface UseNowOptions<Controls extends boolean> {
1212
*/
1313
controls?: Controls
1414

15+
/**
16+
* Start the clock immediately
17+
*
18+
* @default true
19+
*/
20+
immediate?: boolean
21+
1522
/**
1623
* Update interval in milliseconds, or use requestAnimationFrame
1724
*
@@ -32,15 +39,16 @@ export function useNow(options: UseNowOptions<boolean> = {}) {
3239
const {
3340
controls: exposeControls = false,
3441
interval = 'requestAnimationFrame',
42+
immediate = true,
3543
} = options
3644

3745
const now = deepRef(new Date())
3846

3947
const update = () => now.value = new Date()
4048

4149
const controls: Pausable = interval === 'requestAnimationFrame'
42-
? useRafFn(update, { immediate: true })
43-
: useIntervalFn(update, interval, { immediate: true })
50+
? useRafFn(update, { immediate })
51+
: useIntervalFn(update, interval, { immediate })
4452

4553
if (exposeControls) {
4654
return {

0 commit comments

Comments
 (0)