import Log from "../Log";
import Timer from "./Timer";

export default class LoopHelper {
    private intervalId: number = null;
    private readonly handler: Function;
    private timer: Timer;

    constructor(callback: Function) {
        this.handler = callback;
        Log.info('[LoopHelper] 已创建, 方法: ', callback);
    }

    public start(loopGap: number = 1000): void {
        Log.info('[LoopHelper] 已启动, 间隔' + loopGap);
        this.timer = new Timer();
        this.intervalId = window.setInterval(() => {
            try {
                this.handler();
            } catch (e) {
                Log.error(e.message, e.stack);
                throw e;
            }
        }, loopGap);
    }

    public stop(): void {
        // this.counter = 0;
        Log.info('[LoopHelper] 已停止, 运行' + this.timer.getTimeMs());
        window.clearInterval(this.intervalId);
        this.intervalId = null;
    }

    public isRunning(): boolean {
        return this.intervalId !== null;
    }
}