外观
sleep 延迟函数
约 180 字小于 1 分钟
2024-01-01
介绍
提供基于Promise的延迟函数,用于异步编程中的等待操作。
sleep(timer?: number): Promise
- 参数
- timer: 延迟时间,单位毫秒,默认 30ms
- 返回值
<Promise>Promise 对象,等待指定时间后 resolve
示例代码
<template>
<view>
<button @click="startCountdown">开始倒计时</button>
<view v-if="count > 0">
<text>{{ count }}秒后执行操作</text>
</view>
<view v-if="result">
<text>{{ result }}</text>
</view>
</view>
</template>
<script setup lang="uts">
import { ref } from 'vue'
import { sleep } from '@/uni_modules/uview-unix'
const count = ref(5)
const result = ref('')
const startCountdown = async () => {
count.value = 5
result.value = ''
// 倒计时循环
while (count.value > 0) {
await sleep(1000) // 延迟1秒
count.value--
}
// 倒计时结束后执行操作
result.value = '倒计时结束!'
console.log('操作执行完成')
}
</script>