webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.7k stars 188 forks source link

16 - until #2680

Open JJczC-love opened 4 months ago

JJczC-love commented 4 months ago
<script setup lang='ts'>
import { ref, watch } from "vue"
import type { Ref } from "vue";

const count = ref(0)

function until(initial: Ref<number>) {
  function toBe(value: number): Promise<void> {
    return new Promise((resolve) => {
      const unwatch = watch(initial, (val) => {
        if (val === value) {
          unwatch();
          resolve()
        }
      })
    })
  }

  return {toBe }
}

let timer = null;
async function increase() {
  count.value = 0
  if (timer) clearInterval(timer)
  timer = setInterval(() => {
    count.value++
  }, 1000)
  await until(count).toBe(3)
  console.log(count.value === 3) // Make sure the output is true
}

</script>

<template>
  <button @click="increase">
    Increase
  </button>
  <p>{{ count }}</p>
</template>