Typescript 实现倒计时功能 useCountdown

效果图

代码块

useCountdown.ts

import {onUnmounted, reactive, ref, watch} from "vue";

type union = 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds'

export type Remains = Record<union, number>;

/**
 * 创建一个倒计时
 *
 * 用法
 */
export const useCountDown = () => {
    const remainMilliseconds = ref();
    const started = ref(false);
    const finished = ref<boolean>();
    const remains = reactive<Remains>({
        days: 0,
        hours: 0,
        minutes: 0,
        seconds: 0,
        milliseconds: 0,
    });

    const start = (deadline: number) => {
        if (started.value) {
            return
        }
        started.value = true
        loop(deadline)
    }

    const loop = (deadline: number) => {
        if (typeof requestAnimationFrame == 'function') {
            if (started.value) {
                requestAnimationFrame(() => {
                    const nowTime = new Date().getTime();
                    remainMilliseconds.value = deadline - nowTime;
                    finished.value = remainMilliseconds.value <= 0
                    if (finished.value) {
                        stop()
                    }
                    loop(deadline)
                })
            }
        } else {
            // 降级使用定时器
            const interval = setInterval(() => {
                const nowTime = new Date().getTime();
                remainMilliseconds.value = deadline - nowTime;
                finished.value = remainMilliseconds.value <= 0
                if (finished.value) {
                    stop()
                    clearInterval(interval)
                }
            }, 16);
        }
    }

    const stop = () => {
        started.value = false
    }

    watch(remainMilliseconds, (value) => {
        remains.days = Math.max((value / 1000 / 60 / 60 / 24 | 0), 0)
        remains.hours = Math.max((value / 1000 / 60 / 60 % 24 | 0), 0)
        remains.minutes = Math.max((value / 1000 / 60 % 60 | 0), 0)
        remains.seconds = Math.max((value / 1000 % 60 | 0), 0)
        remains.milliseconds = Math.max((value % 1000 | 0), 0)
    })

    onUnmounted(stop)

    return {finished, remains, start, stop}
}

vue

<template>
	{{remains.days}}天
	{{remains.hours}}时
	{{remains.minutes}}分钟
	{{remains.seconds}}秒
</template>

<script setup lang="ts">
	import { watch } from 'vue';
import { useCountDown } from './useCountDown';
	const { remains,finished, start } = useCountDown()
	start(new Date().getTime() + 10 * 10000000)
	watch(finished,(n:boolean)=>{
		if(n){
			alert('done')
		}
	})
</script>

<style lang="scss">
</style>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 LayaMetaX-PGC 中使用 TypeScript 实现倒计时的步骤如下: 1. 创建一个倒计时管理器类 CountdownManager。 ```typescript export default class CountdownManager { private static _instance: CountdownManager; private _countdowns: Countdown[]; private constructor() { this._countdowns = []; } public static get instance(): CountdownManager { if (!this._instance) { this._instance = new CountdownManager(); } return this._instance; } public addCountdown(countdown: Countdown): void { this._countdowns.push(countdown); } public removeCountdown(countdown: Countdown): void { const index = this._countdowns.indexOf(countdown); if (index >= 0) { this._countdowns.splice(index, 1); } } public update(deltaTime: number): void { for (const countdown of this._countdowns) { countdown.update(deltaTime); } } } ``` 2. 创建一个倒计时Countdown。 ```typescript export default class Countdown { private _duration: number; // 倒计时时长,单位秒 private _elapsedTime: number; // 已经经过的时间,单位秒 private _onComplete: Function; // 倒计时结束时的回调函数 private _onUpdate: Function; // 每帧更新时的回调函数 constructor(duration: number, onComplete: Function, onUpdate?: Function) { this._duration = duration; this._elapsedTime = 0; this._onComplete = onComplete; this._onUpdate = onUpdate; CountdownManager.instance.addCountdown(this); } public update(deltaTime: number): void { if (this._elapsedTime >= this._duration) { this._onComplete(); this.stop(); return; } this._elapsedTime += deltaTime; if (this._onUpdate) { this._onUpdate(this._elapsedTime / this._duration); } } public stop(): void { CountdownManager.instance.removeCountdown(this); } } ``` 3. 在场景中创建一个倒计时显示对象 CountdownText。 ```typescript export default class CountdownText extends Laya.Label { private _countdown: Countdown; public startCountdown(duration: number, onComplete: Function, onUpdate?: Function): void { this._countdown = new Countdown(duration, onComplete, onUpdate); } public stopCountdown(): void { if (this._countdown) { this._countdown.stop(); this._countdown = null; } } } ``` 4. 在场景中创建一个倒计时文本框 CountdownText。 ```typescript const countdownText = new CountdownText(); countdownText.text = "0:00"; countdownText.fontSize = 20; countdownText.color = "#ffffff"; countdownText.pos(100, 100); this.addChild(countdownText); ``` 5. 在场景的 update 方法中更新倒计时管理器。 ```typescript this.timer.frameLoop(1, this, () => { CountdownManager.instance.update(this.timer.delta / 1000); }); ``` 6. 在场景中使用 CountdownText 的 startCountdown 方法开始倒计时。 ```typescript countdownText.startCountdown(60, () => { console.log("倒计时结束"); }, (progress: number) => { const minutes = Math.floor((60 - progress * 60) / 60); const seconds = Math.floor(60 - progress * 60) % 60; countdownText.text = `${minutes}:${seconds.toString().padStart(2, "0")}`; }); ``` 这样就可以在 LayaMetaX-PGC 中使用 TypeScript 实现倒计时了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值