useInterval


setInterval 的简单封装

TIP

在组件 mounted 时设置定时器,并在组件 unmounted 时清除定时器

API

const [clear, start] = useInterval(fn, delay, immediate)

Params

参数名描述类型默认值
fn定时器回调Function
delay延时时间number
immediate是否立即执行回调在开启定时器booleanfalse

Result

参数名描述类型
clear用于清除定时器() => void
start用于启动定时器() => void

Example

0

Code

<template>
  <p>{{ count }}</p>
  <button @click="clear">stop</button>
  <button @click="start">restart</button>
</template>

<script>
import { useInterval } from 'vue-compositions'
import { ref } from 'vue'
export default {
  setup() {
    const count = ref(0)
    const [clear, start] = useInterval(() => {
      count.value++
    }, 1000)
    return {
      count,
      clear,
      start
    }
  }
}
</script>