Skip to content
On this page

useCountDown

一个用于管理倒计时的 Hook

Demo

countdown: 0
<template>
<div>{{ timeLeft }}</div>
<button @click="start(30)">start(30)</button>
<button @click="start(10)">start(10)</button>
<button @click="start()">start</button>
<button @click="pause()">pause</button>
<button @click="play()">play</button>
<button @click="stop()">stop</button>
</template>

<script setup lang="ts">
import { useCountDown } from 'v3-use'

const [timeLeft, { start, pause, play, stop }] = useCountDown({
onEnd: () => {
console.log('End of the countdown')
},
interval: 1000,
step: 1,
format: c => `countdown: ${c}`
})
</script>

Usage

import { useCountDown } from 'v3-use'
const [timeLeft, { start, pause, play, stop }] = useCountDown({
  onEnd: () => {
    console.log('End of the time')
  },
  interval: 500,
  step: 1,
})
</script>
import { useCountDown } from 'v3-use'
const [timeLeft, { start, pause, play, stop }] = useCountDown({
  onEnd: () => {
    console.log('End of the time')
  },
  interval: 500,
  step: 1,
})
</script>

Reference

const [timeLeft, actions] = useCountDown<T>(options?: Options)
const [timeLeft, actions] = useCountDown<T>(options?: Options)

Type Declarations

export declare type Options<T> = {
  defaultTimeLeft?: number
  interval?: number
  step?: number
  format?: (left: number) => T
  onEnd?: () => void
}
export declare type Actions = {
  start: (t?: number) => void
  play: () => void
  pause: () => void
  stop: () => void
}
export declare function useCountDown<T>(options?: Options<T>): [Ref<T>, Actions]
export declare type Options<T> = {
  defaultTimeLeft?: number
  interval?: number
  step?: number
  format?: (left: number) => T
  onEnd?: () => void
}
export declare type Actions = {
  start: (t?: number) => void
  play: () => void
  pause: () => void
  stop: () => void
}
export declare function useCountDown<T>(options?: Options<T>): [Ref<T>, Actions]

Params

  • defaultTimeLeft: number — 默认剩余时间 默认值 0
  • interval: number — 循环间隔(ms),默认值 1000
  • step: number — 间隔尺寸,默认值 1
  • format: (left: number) => T — 剩余时长格式化函数,默认值 undefined
  • onEnd: () => void — 结束钩子,默认值 undefined

Result

  • state: Ref<T> — 剩余时间
  • actions: Actions — 操作集合

Actions

  • start: (t?: number) => void — 初始化倒计时函数,可接收初始倒计时间,默认 defaultTimeLeft
  • pause: () => void — 暂停倒计时函数
  • play: () => void — 继续倒计时函数
  • stop: () => void — 终止倒计时函数,倒计时归 0