实现秒表的最有效方法?

Emenpy

我想跟踪用户单击按钮需要多长时间。我已经解决了这个问题,但如果有的话,希望有一个更好的解决方案。这是我所拥有的:

export class MainComponent implements OnInit {

    timer : number = 0;
    intervalId : number;

    constructor() {
      this.intervalId = setInterval(() => {
        this.timer++;
      }, 1000);
    }

    ngOnInit() {}

    buttonClick = function() {
    alert(this.timer);
    this.timer = 0;
    }
}

用于performance.now()获得准确的时间戳记(或回退到new Date().getTime()),并计算UI更新回调中的差异(通过setInterval)。不要用setInterval自己来计算时间-您不能假设setInterval实际上每1000毫秒就会真正调用一次呼叫。

请注意,我还将计时器逻辑移到了ngOnInit函数而不是constructor

export class MainComponent implements OnInit {

    private start: number = null;
    private uiTimerId: number = null;

    constructor() {
    }

    private updateUI(): void {

        let delta = performance.now() - this.start;
        this.someUIElement.textContent = delta.toFixed() + "ms";
    }

    ngOnInit() {

        this.start = parseFloat( window.localStorage.getItem( "timerStart" ) );
        if( !this.start ) {
            this.start = performance.now();
            window.localStorage.setItem( "timerStart", this.start );
        }

        this.uiTimerId = window.setInterval( this.updateUI.bind(this), 100 ); // 100ms UI updates, not 1000ms to reduce UI jitter
    }

    buttonClick = function() {
        if( this.uiTimerId != null ) {
            window.clearInterval( this.uiTimerId );
            window.localStorage.removeItem( "timerStart" );
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章