vuejs-challenges
vuejs-challenges copied to clipboard
16 - until
<script setup lang='ts'>
import { ref, watch } from "vue"
const count = ref(0)
/**
* Implement the until function
*/
function until(initial) {
function toBe(value) {
/*
* 方法:侦听intial值,当其等于传入值value时,停止侦听并解决期约
* 另外一个方法是使用setInterval,但是如果间隔时间太大可能会导致结果不准确,太小又加剧资源占用,所以使用侦听器可能是个更好的方法(个人见解)
*/
return new Promise(resolve=>{
const stopWatcher = watch(initial, ()=>{
if(initial.value == value) {
stopWatcher();
resolve(undefined);
}
})
})
}
return {
toBe,
}
}
async function increase() {
count.value = 0
setInterval(() => {
count.value++
}, 1000)
await until(count).toBe(3)
console.log(count.value === 3) // Make sure the output is true
}
</script>
<template>
<p @click="increase">
Increase
</p>
</template>