AutoPlayer 自动播放类代码分享

72 阅读1分钟

实现代码如下

export class AutoPlayer {
    timer = null;
    index: number = 0;
    isPause = false;
    arr = [];
    callback: Function;

    constructor(arr: Array<any>) {
        this.arr = arr;
    }
    pause() {
        this.clear();
        this.isPause = true;
    }
    next() {
        this.isPause = false;
        this.init();
    }
    init() {
        this.timer = setInterval(() => {
            this.callback(this.index);
            if (this.index == this.arr.length - 1) {
                this.index = 0;
            } else {
                this.index++;
            }
            if (this.isPause) {
                this.clear();
            }
        }, 1000)
    }
    clear() {
        clearInterval(this.timer);
    }
    goIndex(i) {
        this.index = i;
    }
}