我有一个类(通过WebSocket)充当服务器的客户端。我想实现一个定期对服务器进行ping以确定延迟的系统。但是,我担心如果为此目的在类内使用setInterval,它将在对象应被垃圾回收后继续尝试ping。我怎么知道什么时候呼叫clearInterval

代码摘要:

class WSClient extends EventEmitter
{
    private latency: number;
    public get Latency(): number
    { return this.latency; }

    public async ping(): Promise<number>
    { ... }

    public constructor(options)
    {
        super();

        // Do constructor stuff

        setInterval(() => this.ping().then(latency => this.latency = latency), 1000);
    }
}

最佳答案

您可以使用setInterval()并将其保存到变量,然后可以像这样访问该间隔:

class WSClient extends EventEmitter
{
    private latency: number;
    public get Latency(): number
    { return this.latency; }

    public async ping(): Promise<number>
    { ... }

    public constructor(options)
    {
        super();

        // Do constructor stuff

        this.interval = setInterval(() => this.ping()
        .then(latency => this.latency = latency), 1000);
    }
}


然后,当您需要时:

WSClient.interval.clearInterval();

09-07 15:39