Skip to content
On this page

useSleep

暂停程序 - 在设定时间后继续执行

谨慎选择 while暂停方式,其原理是跑满cpu以至于不能执行其他程序

Demo

num: 0

Usage

html
<template>
  <div>
    <p>num: {{ num }}</p>

    <button @click="sleep">暂停3秒执行</button>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useSleep } from '@morehook/core'

const num = ref(0)
let timmer = setInterval(() => {
  num.value++
}, 1000)

async function sleep() {
  clearInterval(timmer)
  await useSleep(3000)
  timmer = setInterval(() => {
    num.value++
  }, 1000)
}
</script>

Type Declarations

typescript
/**
 * 暂停程序 - 在设定时间后继续执行
 * @param time 暂停的时间
 * @param type 暂停方式 while:整个程序暂停  await:暂停某一块逻辑 (默认 await)
 * @returns 如果是 await 方式则返回promise对象,外层直接await
 * @tips 谨慎选择 while暂停方式,其原理是跑满cpu以至于不能执行其他程序,这意味着你点击其他菜单都不会做出反应
 */
export declare function useSleep(
  time: number,
  type?: "while" | "await"
): Promise<unknown> | undefined

Source

SourceDemoDocs