跳到主要內容

useCountdown

分類
導出大小
上次變更
5 天前

useIntervalFn 的封裝器,提供倒數計時器。

範例

🚀
火箭將在 5 秒後發射
倒數計時

用法

js
import { useCountdown } from '@vueuse/core'

const countdownSeconds = 5
const { remaining, start, stop, pause, resume } = useCountdown(countdownSeconds, {
  onComplete() {

  },
  onTick() {

  }
})

您可以使用 ref 來更改初始倒數計時。start() 和 resume() 也接受新的倒數值以用於下次倒數計時。

js
import { shallowRef } from 'vue'
import { useCountdown } from '@vueuse/core'

const countdown = shallowRef(5)
const { start, reset } = useCountdown(countdown, {
})

// change the countdown value
countdown.value = 10

// start a new countdown with 2 seconds
start(2)

// reset the countdown to 4, but do not start it
reset(4)

// start the countdown with the current value of `countdown`
start()

類型宣告

顯示類型宣告
typescript
export interface UseCountdownOptions {
  /**
   *  Interval for the countdown in milliseconds. Default is 1000ms.
   */
  interval?: MaybeRefOrGetter<number>
  /**
   * Callback function called when the countdown reaches 0.
   */
  onComplete?: () => void
  /**
   * Callback function called on each tick of the countdown.
   */
  onTick?: () => void
  /**
   * Start the countdown immediately
   *
   * @default false
   */
  immediate?: boolean
}
export interface UseCountdownReturn extends Pausable {
  /**
   * Current countdown value.
   */
  remaining: ShallowRef<number>
  /**
   * Resets the countdown and repeatsLeft to their initial values.
   */
  reset: (countdown?: MaybeRefOrGetter<number>) => void
  /**
   * Stops the countdown and resets its state.
   */
  stop: () => void
  /**
   * Reset the countdown and start it again.
   */
  start: (countdown?: MaybeRefOrGetter<number>) => void
}
/**
 * Wrapper for `useIntervalFn` that provides a countdown timer in seconds.
 *
 * @param initialCountdown
 * @param options
 *
 * @see https://vueuse.dev.org.tw/useCountdown
 */
export declare function useCountdown(
  initialCountdown: MaybeRefOrGetter<number>,
  options?: UseCountdownOptions,
): UseCountdownReturn

原始碼

原始碼範例文件

貢獻者

IlyaL
Anthony Fu
Anthony Fu
Renato Lacerda
Robin
Neo Fu

變更日誌

v12.8.0 於 2025/3/5
7432f - feat(types): 棄用 MaybeRef 和 MaybeRefOrGetter,改用 Vue 原生類型 (#4636)
v12.6.0 於 2025/2/14
93591 - fix: start() 應該接受自訂初始值 (#4554)
v12.5.0 於 2025/1/22
69ced - feat: 新增函數 (#4125)

根據 MIT 許可證發布。