Skip to content

Instantly share code, notes, and snippets.

@TheVishnuKumar
Created December 27, 2018 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheVishnuKumar/c2da13377abe3ffd601f8db566d27048 to your computer and use it in GitHub Desktop.
Save TheVishnuKumar/c2da13377abe3ffd601f8db566d27048 to your computer and use it in GitHub Desktop.
<template>
<div style="background: white;padding: 20px;border-radius: 6px;">
<div style="font-size: 20px;text-align:center;">{timeVal}</div>
<template if:true={showStartBtn}>
<lightning-button label="Start" onclick={start} style="margin-left: 145px;"></lightning-button>
</template>
<template if:false={showStartBtn}>
<lightning-button label="Stop" onclick={stop} style="margin-left: 145px;"></lightning-button>
</template>
<lightning-button label="Reset" onclick={reset} style="margin-left: 10px;"></lightning-button>
</div>
</template>
import { LightningElement, track } from 'lwc';
export default class Stopwatch extends LightningElement {
@track showStartBtn = true;
@track timeVal = '0:0:0:0';
timeIntervalInstance;
totalMilliseconds = 0;
start(event) {
this.showStartBtn = false;
var parentThis = this;
// Run timer code in every 100 milliseconds
this.timeIntervalInstance = setInterval(function() {
// Time calculations for hours, minutes, seconds and milliseconds
var hours = Math.floor((parentThis.totalMilliseconds % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((parentThis.totalMilliseconds % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((parentThis.totalMilliseconds % (1000 * 60)) / 1000);
var milliseconds = Math.floor((parentThis.totalMilliseconds % (1000)));
// Output the result in the timeVal variable
parentThis.timeVal = hours + ":" + minutes + ":" + seconds + ":" + milliseconds;
parentThis.totalMilliseconds += 100;
}, 100);
}
stop(event) {
this.showStartBtn = true;
clearInterval(this.timeIntervalInstance);
}
reset(event) {
this.showStartBtn = true;
this.timeVal = '0:0:0:0';
this.totalMilliseconds = 0;
clearInterval(this.timeIntervalInstance);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="Stopwatch">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment