在Javascript倒计时器中显示毫秒数

时间:2017-10-24 02:55:42

标签: javascript angular typescript timer

我正在创建一个使用start和stop方法的倒数计时器,以及一个adjust方法。一旦计时器达到59秒或更短,我想显示毫秒,但我找不到正确的方法。继承我的代码:

JavaScript的:

import { Component, OnInit } from '@angular/core';
import * as p5 from 'p5/lib/p5';

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

    timer: number = 60;
    intervalId: number = -1;


   constructor() {
   }

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

      if (this.timer <= 0) {
        this.stop();
      }

    }


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

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

    timeIt() {
     this.timer--;
     if (this.timer == 0) {
       clearInterval(this.intervalId);
     }
    }

    adjustTime() {
      this.stop();
      var newTime = prompt("Enter adjusted time in seconds: ");
      if (newTime == null || newTime == "" || newTime.match(/[a-z]/i) 
|| newTime.match(/[`|\\/~^:,;?!&%$@*+=-_]/)) {
       alert("Enter a number!")
       this.timer = this.timer;
      } else {
          this.timer = parseInt(newTime);
      }
    }

    convertSeconds(s) {
      var minutes = Math.floor(s / 60);
      var seconds = s % 60;

      if (this.timer >= 60)
        return p5.prototype.nf(minutes, 1) + ':' + 
p5.prototype.nf(seconds, 2);
      else if (this.timer < 10)
        return p5.prototype.nf(seconds, 1) + '.millis';
      else 
        return p5.prototype.nf(seconds, 2) + '.millis';
    }

}

HTML:

<div class="clock">
    <h1>{{ convertSeconds(timer) }}</h1>
    <button (click)="startStop()">Start/Stop</button>
    <button (click)="adjustTime()">Adjust Time</button>
</div>

在HTML中调用convertSeconds()方法,其参数是计时器上的秒数。在表格&#39; 59.9&#39;,&#39; 10.5&#39;中显示毫秒的最佳方法是什么?等等?

0 个答案:

没有答案