We can create a stopwatch using Vue.js by using built in functions. In this article, we’ll find out how to make a simple stopwatch.
To start, we create new project with the Vue CLI by running npx @vue/cli
.
We then select the default options to create a new Vue project.
Next, we can write the following code:
<template>
<div id="app">
<button @click="start">Start</button>
<button @click="stop">Stop</button>
<button @click="reset">Reset</button>
<p>{{formattedElapsedTime}}</p>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
elapsedTime: 0,
timer: undefined
};
},
computed: {
formattedElapsedTime() {
const date = new Date(null);
date.setSeconds(this.elapsedTime / 1000);
const utc = date.toUTCString();
return utc.substr(utc.indexOf(":") - 2, 8);
}
},
methods: {
start() {
this.timer = setInterval(() => {
this.elapsedTime += 1000;
}, 1000);
},
stop() {
clearInterval(this.timer);
},
reset() {
this.elapsedTime = 0;
}
}
};
</script>
In the code above, we have the Start, Stop, and Reset buttons. Then we click thev Start, the start
method is run, which creates the timer with setInterval
and the this.elapsedTime
state is updated.
The elapsedTime
is converted to a formatted time string with minutes and seconds with the formattedElapsedTime
computed property,
The Stop button runs the stop
method when it’s clicked, which calls clearInterval
to clear the timer.
The reset
method is called by the Reset button and resets this.elapsedTime
to 0.
Then we’ll see the stopwatch run when we click Start and the timer stops when we click Stop.
The stopwatch goes back to 0 after we click Reset.
Conclusion
We can create a Vue.js stopwatch without adding extra libraries. We just have to use setInterval
and clearInterval
to start and stop the stopwatch respectively.
3 replies on “Create a Vue.js Stopwatch”
Thanks, you saved my day. It’s simple, clean and easy to understand.
There is an bug that appears when you lcik the start button multiple times.
There are several ways to fix it:
One way would be to only show the start or the stop button and the other way would be this:
start() {
//check if interval is already running
if (!this.timer) {
this.timer = setInterval(() => {
this.elapsedTime += 1000;
}, 1000);
}
}
same for stop replace stop with:
if (this.timer) {
clearInterval(this.timer)
this.timer = undefined;
}
but thank you for the tutorial it saved my evening