在设计秒表时返回NaN

时间:2017-02-14 06:09:23

标签: angular ionic2

这就是工作 我正在尝试创建一个秒表,点击开始按钮它应该开始和重置一切应该是0

import { Component } from '@angular/core';

@Component({
    selector: 'page-login',
    templateUrl: 'login.html'
})

export class LoginPage {

public time = 0;
    public running = 0;
constructor(   ) { }

starttime(){
        console.log("timer started");
        if( this.running == 0){
            this.running = 1;
            this.adder()
        }else{
            this.running = 0;
        }
   }

    reset(){
        console.log("timer reset");
        this.running = 0;
        this.time = 0;

    }
    adder(){

    console.log("timer incrementor");
    if(this.running == 1){
        setTimeout(()=>{ 
            this.time++;
            var mins = Math.floor(this.time/10/60);
            var sec = Math.floor(this.time / 10 );
            var tens = this.time/10;

            console.log( mins + ':' +  sec  + ':' + tens);   
            this.adder()  

        },100)
    }

}

    }

}

 <button ion-button block (click)="starttime()">starttime</button>
        <button ion-button block (click)="reset()">reset</button>
{{display the timer here}}

我需要定时器才能启动并且应该实时可见,在停止它应该重置为0,我尝试了上面的代码,但它返回“NaN” 有人可以帮我吗

enter image description here

2 个答案:

答案 0 :(得分:0)

您从未设置this.time。您有一个reset()方法可以执行此操作,但您不会调用它。因此this.time未定义,在通过Math.floor时返回NaN。在构造函数中设置this.time,或在启动计时器之前调用reset()

答案 1 :(得分:0)

更改

  setTimeout(function(){
                this.time++;
                var mins = Math.floor(this.time/10/60);
                var sec = Math.floor(this.time / 10 );
                var tens = this.time/10;

                console.log( mins + ':' +  sec  + ':' + tens);              

            },100)

  setTimeout(()=>{ // <------------change here
                this.time++;
                var mins = Math.floor(this.time/10/60);
                var sec = Math.floor(this.time / 10 );
                var tens = this.time/10;

                console.log( mins + ':' +  sec  + ':' + tens);              

            },100)

由于您使用的是function而不是=>,因此this未引用该组件