【问题标题】:create a stopwatch in angular 6在 Angular 6 中创建秒表
【发布时间】:2019-03-04 11:47:47
【问题描述】:

我正在使用角度。我想实现秒表。我有一个包含一个或多个对象的列表。我有一个开始计时器和结束每个项目的计时器按钮。当我点击开始按钮时,这应该启动特定项目的计时器,当我点击结束计时器按钮时,这应该暂停计时器,以便我可以重新开始计时。但一次只能运行一个计时器。如果项目 A 计时器已启动并且如果单击项目 B 的开始计时器按钮,则它应该暂停前一个计时器并为项目 B 启动新计时器。

allUserTaskArr = [
    {
      'name': 'abc',
     'id':1,
     'start': true,
     'end': false
    },
     {
      'name': 'xyz',
     'id':1,
     'start': true,
     'end': false
    }

  ];
 
 startTask (item) {
    if(item.start) {
      item.end =  true;
      item.start= false;
    } 
  }

  EndTask (item) {
    if(item.end) {
      item.end =  false;
      item.start= true;
    }
  }
<div class="row no-gutters">
  <div class="card width hr" *ngFor="let item of allUserTaskArr">
    <div class="card-header">
      {{item.due | date}}
    </div>
    <div class="card-body pad-125">
      <div class="row no-gutters">
        <div class="col-md-12">
          {{item.name}}
          <div class="float-right">
            <button class="btn btn-info mar-l-r-0-5" *ngIf="item.start" (click)="startTask(item)">Start Timer</button>
            <button class="btn btn-danger mar-l-r-0-5" *ngIf="item.end" (click)="EndTask(item)">End Timer</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

【问题讨论】:

    标签: javascript jquery angular typescript angular-timer


    【解决方案1】:

    您需要创建一个计时器,它是您可以订阅的 Observable。在回调中执行操作。例如:

    在组件中:

    import { timer } from "rxjs";
    
    ngOnInit() {
        timer(0, 1000).subscribe(ellapsedCycles => {
          if(this.isRunning) {
            this.time--;
          }
        });
      }
    
    toggleTimer() {
        this.isRunning = !this.isRunning;
      }
    

    在模板中:

    <button (click)="toggleTimer()">Toggle timer</button>
    <div>{{ time }}</div>
    

    【讨论】:

      【解决方案2】:

      创建一个每秒增长的计时器,然后将时间转换为显示格式

         timer(0, 1000).subscribe(ec => {
                this.time++;
                this.timerDisplay = this.getDisplayTimer(this.time);
              });
      
      getDisplayTimer(time: number) {
          const hours = '0' + Math.floor(time / 3600);
          const minutes = '0' + Math.floor(time % 3600 / 60);
          const seconds = '0' + Math.floor(time % 3600 % 60);
      
          return {
            hours: { digit1: hours.slice(-2, -1), digit2: hours.slice(-1) },
            minutes: { digit1: minutes.slice(-2, -1), digit2: minutes.slice(-1) },
            seconds: { digit1: seconds.slice(-2, -1), digit2: seconds.slice(-1) },
          };
        }`
      

      【讨论】:

        【解决方案3】:

        您正在启动和结束同一个计时器,因为您传递了 foreach 循环的当前 item。所以你改变了同一个项目/计时器的属性。

        要解决这个问题,您需要找到当前正在运行的项目/计时器,因此对于 startTask 方法,请执行以下操作:

        startTask (item) {
           // Find current running timer
           var runningTimer = this.allUserTaskArr.find(ti => ti.start === true);
           // Stop this timer
           runningTimer.start = false;
           runningTimer.end = false;
        
           // Start the timer you pressed
           item.start = true;
        }
        

        【讨论】:

          【解决方案4】:

          秒表动态设定值

            export class TimerComponent implements OnDestroy {
                clock: any;
                minutes: any = '00';
                seconds: any = '00';
                milliseconds: any = '00';
                hours:any = '00';
                
                @Input() start: boolean;
                @Input() showTimerControls: boolean;
              
                constructor() {
              
                }
                ngOnChanges(changes: SimpleChanges) {
                  console.log(changes['start']);
                  if (changes['start'].currentValue) {
                    this.startTimer();
                  }
                  else{
                    this.clearTimer();
                  }
                }
              
                laps: any = [];
                counter: number;
                timerRef;
                running: boolean = false;
                startText = 'Start';
              
              
                startTimer() {
                  // const source = timer(0, Date.now());
                  // const subscribe = source.subscribe(val => console.log(val));
                  this.running = !this.running;
                  if (this.running) {
                    this.startText = 'Stop';
                   const startTime = Date.now() - (this.counter || 0);
                    // const startTime = Date.now() - (this.counter || 5989395);
              
                    this.timerRef = setInterval(() => {
                      
                      this.counter  = Math.abs(new Date('July 12, 2020 20:00:00').getTime() - new Date().getTime());
                      // this.counter = Date.now() - startTime;
                      // console.log(Date.now());
                      // console.log(startTime);
                      // console.log(this.counter);
                      // this.milliseconds = Math.floor(Math.floor(this.counter % 1000) / 10).toFixed(0);
                      // this.minutes = Math.floor(this.counter / 60000);
                      // this.seconds = Math.floor(Math.floor(this.counter % 60000) / 1000).toFixed(0);
                      // this.hours = Math.floor(this.counter / 3600000);
              
                      this.hours  = Math.floor((this.counter % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                      this.minutes  = Math.floor((this.counter % (1000 * 60 * 60)) / (1000 * 60));
                      this.seconds = Math.floor((this.counter % (1000 * 60)) / 1000);
                      //console.log(this.counter);
                      if (this.counter < 0) {
                        this.clearTimer();
                        console.log('expired')
                      }
                       if (Number(this.hours) < 10) {
                        this.hours = '0' + this.hours;
                      } else {
                        this.hours = '' + this.hours;
                      }
                      if (Number(this.minutes) < 10) {
                        this.minutes = '0' + this.minutes;
                      } else {
                        this.minutes = '' + this.minutes;
                      }
                      if (Number(this.seconds) < 10) {
                        this.seconds = '0' + this.seconds;
                      } else {
                        this.seconds = '' + this.seconds;
                      }
                    });
                  } 
              <div class="container">
                <section class="timer-counter-label">
                  <div *ngIf="counter" [ngClass]="{blink: !running}">
                    <span>{{hours}}:</span><span>{{minutes}}:</span><span>{{seconds}}:</span> <span>{{milliseconds}}</span> </div>
                  <div *ngIf="!counter">
                    <!-- <span class="blink timer-start-text">Press Start</span> -->
                    <!-- <br> -->
                    <span>{{hours}}:</span><span>{{minutes}}:</span><span>{{seconds}}:</span> <span>{{milliseconds}}</span>
                  </div>
                </section>
                <div class="timer-button-container" *ngIf="showTimerControls">
                  <button class="timer-button" (click)="startTimer()">
                    {{ startText }}
                  </button>
                  <button [disabled]='!counter' [ngClass]="{'disabled': !counter}" class="timer-button" (click)="lapTimeSplit()">Lap</button>
                  <button class="timer-button" (click)="clearTimer()">Clear</button>
                  <br>
                  <div *ngFor="let lap of laps;let i = index">
                    <div> &#9873; <b>Lap {{i+1}} ::</b>  {{lap}}</div>
                    <br>
                  </div>
                </div>
              </div>
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-05-23
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多