以下是在 Egret 中使用 TypeScript 编写的一个简单延迟器:

class DelayedTask {
    private _callback: Function;
    private _delay: number;
    private _timerId: number;

    constructor(callback: Function, delay: number) {
        this._callback = callback;
        this._delay = delay;
        this._timerId = null;
    }

    public start(): void {
        if (this._timerId) {
            this.stop();
        }
        this._timerId = egret.setTimeout(this._callback.bind(this), this._delay);
    }

    public stop(): void {
        egret.clearTimeout(this._timerId);
        this._timerId = null;
    }
}

使用方法:

let task = new DelayedTask(() => {
    console.log('Task executed!');
}, 1000);
task.start();

该代码创建了一个DelayedTask类,该类可以在指定的延迟时间后执行回调函数。start()方法启动延迟器,并在指定的延迟时间后执行回调函数。stop()方法停止延迟器并取消已激活的回调函数。

Egret TypeScript 延迟器实现 - 轻松延迟执行代码

原文地址: https://www.cveoy.top/t/topic/oE0o 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录