jeudi 27 octobre 2016

Stopwatch running slow - Javascript / Ember.js

I have a stopwatch that I am running as an ember.js controller, and it is running just a tad slow, so over time it falls behind. Trying to determine how to best speed this up to time accurately. Not sure if this is being caused by browser lag, or if the system isn't happy running this process at this speed.

//timer.js
import Ember from 'ember';

export default Ember.Controller.extend({

  state: 'reset',

  tick: 0,
  seconds: 0,
  minutes: 0,
  lapTime: 0,

  isResetState: Ember.computed.equal('state', 'reset'),
  isRunState: Ember.computed.equal('state', 'run'),
  isPauseState: Ember.computed.equal('state', 'pause'),
  isLapState: Ember.computed.equal('state', 'lap'),

  incrementTick(startDate) {
    let currentDate = new Date();
    if (this.get('isRunState') || this.get('isLapState')) {
      this.incrementProperty('tick', currentDate.valueOf() - startDate.valueOf());
      Ember.run.next(this, 'incrementTick', new Date());
    }
    if (this.tick > 999) {
      this.set('tick', 0);
      this.incrementProperty('seconds', 1);
    }
    if (this.seconds > 59) {
      this.set('seconds', 0);
      this.incrementProperty('minutes', 1);
    }
  },

  actions: {
    start() {
      this.set('state', 'run');
      this.incrementTick(new Date());
    },

    stop() {
      this.set('state', 'pause');
    },

    reset() {
      this.set('state', 'reset');
      this.set('tick', 0);
      this.set('seconds', 0);
      this.set('minutes', 0);
    },

    hold() {
      this.set('lapTime', this.get('tick'));
      this.set('state', 'lap');
    },

    continue() {
      this.set('state', 'run');
    },
  },
});




Aucun commentaire:

Enregistrer un commentaire