> For the complete documentation index, see [llms.txt](https://laterly.gitbook.io/hooks-vue3/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://laterly.gitbook.io/hooks-vue3/usecountdown.md).

# useCountDown

#### 基础用法

```html
<template>
  <div>
    <div v-if="isRunningCountDown">
      <button>{{currentCounrDown.seconds}} s</button>
      <button
        @click="
          {
            stopCountDown();
          }
        "
      >
        停止倒计时
      </button>
      <button
        @click="
          () => {
            startCountDown(6 * 1000);
          }
        "
      >
        重新开始倒计时
      </button>
    </div>

    <button
      v-else
      @click="
        () => {
          startCountDown();
        }
      "
    >
      手动触发开始倒计时6秒
    </button>
  </div>
</template>

<script setup lang="ts">

import { useCountDown } from "hooks-vue3";
const {
  isRunning: isRunningCountDown,
  current: currentCounrDown,
  start: startCountDown,
  stop: stopCountDown,
} = useCountDown({
  //倒计时6秒
  time: 6 * 1000,
  //变化时间间隔（毫秒）
  interval: 1000,
  //默认true,设置为false，需要手动触发调用start
  autoStart: false,
  //倒计时改变时触发的回调函数
  onChange: (current) => {
    console.log("当前时间current", current);
  },
  //倒计时结束时触发的回调函数
  onEnd: () => {
    console.log("结束倒计时");
  },
});
</script>

```

### API

```typescript
const {
  isRunning,
  current,
  start,
  stop,
} = useCountDown({
  //倒计时，秒为单位
  time: number,
  //变化时间间隔（毫秒），默认1000
  interval: number,
  //默认true,设置为false，需要手动触发调用start
  autoStart: false,
  //倒计时改变时触发的回调函数
  onChange: (current) => {
    console.log("当前时间current", current);
  },
  //倒计时结束时触发的回调函数
  onEnd: () => {
    console.log("结束倒计时");
  },
});
```

### 参数

```typescript
type CurrentTime = {
  days: number;
  hours: number;
  total: number;
  minutes: number;
  seconds: number;
  milliseconds: number;
};

type UseCountDownActions = {
  isRunning?: Ref<boolean>;
  start: (time?: number) => void; //手动触发倒计时
  stop: () => void; //停止触发倒计时
  current: Ref<CurrentTime>;
};

type UseCountDownOptions = {
  time: number; //剩余时间（毫秒）
  interval?: number; //变化时间间隔（毫秒）
  immediate?: boolean; //是否立即触发
  autoStart?: boolean; //是否自动开始倒计时
  onChange?: (current: CurrentTime) => void; //变化的回调函数
  onEnd?: () => void; //倒计时结束触发
};

function useCountDown({
  time,
  interval = 1000,
  immediate = false,
  autoStart = true,
  onChange,
  onEnd,
}: UseCountDownOptions): UseCountDownActions
```
