Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useTimeout): add pause and resume methods #3889

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 3 additions & 3 deletions packages/shared/useTimeout/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { ComputedRef } from 'vue-demi'
import type { ComputedRef, ShallowRef } from 'vue-demi'
import { computed } from 'vue-demi'
import type { UseTimeoutFnOptions } from '../useTimeoutFn'
import { useTimeoutFn } from '../useTimeoutFn'
import type { Fn, Stoppable } from '../utils'
import type { Fn, Pausable, Stoppable } from '../utils'
import { noop } from '../utils'

export interface UseTimeoutOptions<Controls extends boolean> extends UseTimeoutFnOptions {
Expand All @@ -26,7 +26,7 @@ export interface UseTimeoutOptions<Controls extends boolean> extends UseTimeoutF
* @param options
*/
export function useTimeout(interval?: number, options?: UseTimeoutOptions<false>): ComputedRef<boolean>
export function useTimeout(interval: number, options: UseTimeoutOptions<true>): { ready: ComputedRef<boolean> } & Stoppable
export function useTimeout(interval: number, options: UseTimeoutOptions<true>): { ready: ComputedRef<boolean> } & Stoppable & Pausable & { timeLeft: ShallowRef<number> }
export function useTimeout(interval = 1000, options: UseTimeoutOptions<boolean> = {}) {
const {
controls: exposeControls = false,
Expand Down
15 changes: 13 additions & 2 deletions packages/shared/useTimeoutFn/demo.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useTimeoutFn } from '@vueuse/core'

const defaultText = 'Please wait for 3 seconds'
const text = ref(defaultText)
const { start, isPending } = useTimeoutFn(() => {
const { start, isPending, pause, resume, isActive, timeLeft } = useTimeoutFn(() => {
text.value = 'Fired!'
}, 3000)

Expand All @@ -15,8 +15,19 @@ function restart() {
</script>

<template>
<p>{{ text }}</p>
<p>
{{ text }}
<template v-if="isPending && !isActive">
- Paused - Time left: {{ timeLeft }}
</template>
</p>
<button :class="{ disabled: isPending }" @click="restart()">
Restart
</button>
<button v-if="isPending && isActive" @click="pause()">
Pause
</button>
<button v-if="isPending && !isActive" @click="resume()">
Resume
</button>
</template>
29 changes: 29 additions & 0 deletions packages/shared/useTimeoutFn/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,33 @@ describe('useTimeoutFn', () => {
expect(isPending.value).toBe(false)
expect(callback).toBeCalled()
})

it('supports pause control', async () => {
vi.useFakeTimers()

const callback = vi.fn()
const { pause, resume, isActive, timeLeft } = useTimeoutFn(callback.bind(null, 1, 2, 3), 50)

vi.advanceTimersByTime(20)
pause()
expect(isActive.value, 'Timer should not be active').toBe(false)
expect(timeLeft.value, 'Time left should be the original timeout minus time passed').toBe(30)

resume()
vi.advanceTimersByTime(20)
pause()
expect(isActive.value, 'Timer should not be active').toBe(false)
expect(timeLeft.value, 'Time left should be the original timeout minus time passed').toBe(10)

vi.advanceTimersByTime(11)
expect(timeLeft.value, 'Time left should be the same while it\'s paused').toBe(10)
expect(callback).not.toBeCalled()

resume()
expect(isActive.value, 'Timer should be active again').toBe(true)
vi.advanceTimersByTime(11)
expect(callback).toBeCalledWith(1, 2, 3)

vi.useRealTimers()
})
})
49 changes: 43 additions & 6 deletions packages/shared/useTimeoutFn/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { ShallowRef } from 'vue-demi'
import { readonly, ref } from 'vue-demi'
import type { AnyFn, MaybeRefOrGetter, Stoppable } from '../utils'
import type { AnyFn, MaybeRefOrGetter, Pausable, Stoppable } from '../utils'
import { toValue } from '../toValue'
import { tryOnScopeDispose } from '../tryOnScopeDispose'
import { isClient } from '../utils'
Expand All @@ -24,13 +25,17 @@ export function useTimeoutFn<CallbackFn extends AnyFn>(
cb: CallbackFn,
interval: MaybeRefOrGetter<number>,
options: UseTimeoutFnOptions = {},
): Stoppable<Parameters<CallbackFn> | []> {
): Stoppable<Parameters<CallbackFn> | []> & Pausable & { timeLeft: ShallowRef<number> } {
const {
immediate = true,
} = options

const isPending = ref(false)

const isActive = ref(false)
const startedAt = ref(-1)
const timeLeft = ref(-1)

let timer: ReturnType<typeof setTimeout> | null = null

function clear() {
Expand All @@ -42,18 +47,46 @@ export function useTimeoutFn<CallbackFn extends AnyFn>(

function stop() {
isPending.value = false
isActive.value = false
clear()
}

function start(...args: Parameters<CallbackFn> | []) {
clear()
isPending.value = true
function setTimer(ms: number, ...args: Parameters<CallbackFn> | []) {
timer = setTimeout(() => {
isPending.value = false
isActive.value = false
timer = null

cb(...args)
}, toValue(interval))
}, ms)
}

function start(...args: Parameters<CallbackFn> | []) {
clear()
startedAt.value = new Date().getTime()
isPending.value = true
isActive.value = true
timeLeft.value = toValue(interval)

setTimer(toValue(interval), ...args)
}

function pause() {
if (timer) {
clearTimeout(timer)
timer = null

isActive.value = false
const diff = timeLeft.value - (new Date().getTime() - startedAt.value)
timeLeft.value = diff
}
}

function resume(...args: Parameters<CallbackFn> | []) {
startedAt.value = new Date().getTime()
isActive.value = true

setTimer(timeLeft.value, ...args)
}

if (immediate) {
Expand All @@ -68,5 +101,9 @@ export function useTimeoutFn<CallbackFn extends AnyFn>(
isPending: readonly(isPending),
start,
stop,
timeLeft: readonly(timeLeft),
isActive: readonly(isActive),
pause,
resume,
}
}