2017-10-18 18 views
0

角度4で単純なタイマーを作成しようとしていますが、毎秒チックアップしますが、次のコードを実行すると速すぎます。角4タイマーが速すぎる

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

@Component({ 
    selector: 'app-clock', 
    templateUrl: './clock.component.html', 
    styleUrls: ['./clock.component.css'] 
}) 
export class ClockComponent implements OnInit { 

    timer: number = 0; 

    constructor() { 

    } 

    ngOnInit() { 
    } 

    timeIt() { 
    this.timer++; 
    } 

    upTick() { 
    return setInterval(() => { 
     this.timeIt() 
    }, 1000); 
    } 


} 

// HTMLここで間違って何が起こっているか確認してください、ではないパラメータはtimeit(単独のsetInterval()関数を使ってJavaScriptでこのコードを実装する)と、各第二のための1000点の作品

<p> 
{{ upTick() }} 
<button 
    type="submit" 
    (click)="startStop()">Start/Stop 
</button> 
</p> 

タイプスクリプト

+1

各呼び出しになってしまったビットは 'upTick'は、インターバルタイマーを起動し、あなたのコードを変更します。また、テンプレートがレンダリングされるときに 'upTick'がAngularによって複数回呼び出されるため、複数の同時インターバルタイマーが実行されます。 – cartant

+0

これは意味があります、タイマー変数をTypeScriptファイルで更新し、htmlファイルに{timer}を渡す方法はありますか? – Liam

答えて

0

コメントに記載されているように、角度テンプレートは複数回レンダリングされます。

したがって、一度に実行できるインターバルは1つにする必要があります。

setInterval()は、あなたがそれを処理できるようにIDを返します。

私はこの

@Component({ 
    selector: 'main', 
    template: ` 
    <div> 
    {{timer}} 
    <button (click)="startStop()">Start/Stop</button> 
    </div> 
    ` 
}) 
export class MainComponent implements OnInit { 

    timer : number = 0; 
    intervalId : number; 

    constructor() { 
    } 


    start() { 
     this.intervalId = setInterval(() => { 
     this.timeIt() 
     }, 1000); 
    } 

    stop() { 
     clearInterval(this.intervalId); 
     this.intervalId = -1; 
    } 

    startStop() { 
     if(this.intervalId == -1) { 
     this.start(); 
     } else { 
     this.stop(); 
     } 
    } 

    timeIt() { 
    this.timer++; 
    } 

    ngOnInit() { 
     this.start(); 
    } 
} 

http://plnkr.co/edit/Mu1k05WXHhijWDjahd0Y?p=preview

+0

これは助けてくれてありがとう! – Liam

関連する問題