0

I have code that starts a stopwatch, updates milliseconds variable every 1 millisecond, and displays the number of hours, minutes, seconds, and milliseconds elapsed.

However the displayed elapsed seconds aren't realistic - 10 seconds can pass, while the stopwatch would only show 3 seconds elapsed

enter image description here

This it the code:

<template>
  <div>
    {{ this.duration(this.milliseconds) }}
  </div>
</template>

<script>
export default {
  name: "App",
  components: {},

  data() {
    return {
      timeValue: String,
      milliseconds: Number,
    };
  },

  created() {
    this.milliseconds = 0;

    setInterval(() => {
      this.milliseconds++;
    }, 1);
  },

  methods: {
    duration(millisecondsData) {
      let milliseconds = millisecondsData % 1000;
      millisecondsData = (millisecondsData - milliseconds) / 1000;

      let seconds = millisecondsData % 60;
      millisecondsData = (millisecondsData - seconds) / 60;

      let minutes = millisecondsData % 60;
      let hours = (millisecondsData - minutes) / 60;

      return [
        this.format(hours),
        this.format(minutes),
        this.format(seconds),
        this.format(milliseconds),
      ].join(":");
    },

    format(n) {
      return (~~n).toString().padStart(2, "0");
    },
  },
};
</script>

Code fiddle: https://codesandbox.io/s/little-forest-tckk57?file=/src/App.vue:0-964

I've also tried running pure JS code in an IDE, and it runs fine (the seconds elapsed match real time), however running the same JS code inside browser console shows the same result as the Vue code.

parsecer
  • 4,758
  • 13
  • 71
  • 140
  • My first guess would be that the vue reactivity ticks take longer than one millisecond. Why not set a starting time and just use the difference of `now - start` to update the timer ? – Niro Feb 23 '23 at 18:58

0 Answers0