import { ref } from 'vue'

// 倒计时
export function useCountDown() {
    const countNum = ref(0)
    const countInterval = ref(null)

    const startCountDown = num => {
        countNum.value = Number(num)
        clearCountDown()
        countInterval.value = setInterval(() => {
            if (countNum.value === 0) {
                clearInterval(countInterval.value)
                countInterval.value = null
                return
            }
            countNum.value--
        }, 1000)
    }

    const clearCountDown = () => {
        if (countInterval.value) {
            clearInterval(countInterval.value)
        }
    }

    return { countNum, startCountDown, clearCountDown }
}


// 防抖
export function useDebounce(cb, delay = 150) {
    const timer = ref(null)

    const handler = () => {
        if (timer.value) {
            clearTimeout(timer.value)
            timer.value = setTimeout(() => {
                cb()
            }, delay)
        } else {
            timer.value = setTimeout(() => {
                cb()
            }, delay)
        }
    }

    return { handler }
}
