角setTimeout运行太多次了

时间:2019-10-16 04:28:46

标签: javascript angular intervals

我有一个由两个或多个其他组件实现的日志查看器组件。该日志查看器使用setTimeout创建一个间隔循环以从文件中获取数据。我的问题是,由于此组件已导入其他组件中,因此计时器会为每个组件分别运行,因此每秒可读取多个文件。

是否可以避免这种情况,并且无论使用该组件的组件数量多少,仅运行一次计时器?

以下是创建setTimeout间隔的日志查看器组件的代码:

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { LogsService } from '../../services/logs.service';
import { HelperService } from '../../services/helper.service';

@Component({
    selector: 'app-logger',
    templateUrl: './logger.component.html',
    styleUrls: ['./logger.component.scss']
})
export class LoggerComponent implements OnInit {
    @ViewChild('scroller', {static: false}) scroller: ElementRef;

    logClassName: string = 'logs shadow close';
    logs: string = '';
    logTS: number = 0;
    logTimer;
    scrollTop: number = 0;

    constructor(
        private logsService: LogsService,
        private h: HelperService
    ){}

    ngOnInit(): void {
        this.getLogs();
    }

    ngOnDestroy(): void {
        if (this.logTimer) window.clearTimeout(this.logTimer);
    }

    toggle(type){
        switch (type)
        {
            case 'open': this.logClassName = 'logs shadow open'; break;
            case 'close': this.logClassName = 'logs shadow close'; break;
            case 'full': this.logClassName = 'logs shadow full'; break;
        }
    }

    getLogs(){
        this.logsService.fetch(this.logTS).subscribe(
            response => {
                this.logs += response.data.join('');
                this.logTS = response.ts;

                window.setTimeout(() => {
                    this.scrollTop = this.scroller.nativeElement.scrollHeight;
                }, 100);

                this.setLogTimer();
            },
            error => {
                this.h.lg('unable to fetch logs', 'error');
                this.logs = '<p>Unable to fetch logs</p>';

                this.setLogTimer();
            }
        );
    }

    setLogTimer(){
        if (this.logTimer) window.clearTimeout(this.logTimer);

        this.logTimer = window.setTimeout(() => {
            this.getLogs();
        }, 1000);
    }
}

2 个答案:

答案 0 :(得分:0)

为解决此问题,Angular提供了Singleton services。您可以在Encoder 2中移动City.pluck(:id, :name).to_h setLogTimer()

答案 1 :(得分:0)

问题是this.logTimer与组件实例相关联,并且每个实例都不同,并且永远不会被取消的解决方案是使用某些共享服务来执行文件读取,如

@Injectable(provideIn:'root')
export class SomeService{

    setLogTimer(){
            if (this.logTimer) window.clearTimeout(this.logTimer);

            this.logTimer = window.setTimeout(() => {
                this.getLogs();
            }, 1000);
        }

}

然后在组件中使用此服务,例如

this.someService.setLogTimer()