You will learn the following things

  1. How to Create a component
  2. How to use SetInterval
  3. How to convert second to minutes and Hours
  4. How to use local storage
  5. How to persist the state
  6. How to start, stop and reset the watch

Video Tutorial

Steps and code

  1. Create Lwc component stopWatch and add the following code to the respective files.

stopWatch.html

2. In the stopWatch.html we are creating the card component and within the card with have heading, timer and button groups

stopWatch.js

import { LightningElement } from 'lwc';

export default class StopWatch extends LightningElement {

    timer = '0'
    timerRef
    
    actionHandler(event){
        const {label} = event.target
        if(label === 'Start'){
            this.setTimer()
        }
        if(label === 'Stop'){
            window.clearInterval(this.timerRef)
            window.localStorage.removeItem('startTimer')
        }
        if(label === 'Reset'){
            this.timer='0'
            window.clearInterval(this.timerRef)
            window.localStorage.removeItem('startTimer')
        }
        
    }
    StartTimerHandler(){
        const startTime = new Date()
        window.localStorage.setItem('startTimer', startTime)
        return startTime
    }
    setTimer(){
        const startTime = new Date( window.localStorage.getItem("startTimer") || this.StartTimerHandler())
        this.timerRef = window.setInterval(()=>{
            const secsDiff = new Date().getTime() - startTime.getTime()
            this.timer = this.secondToHms(Math.floor(secsDiff/1000))
        }, 1000)
    }

    secondToHms(d){
        d = Number(d)
        const h = Math.floor(d / 3600);
        const m = Math.floor(d % 3600 / 60);
        const s = Math.floor(d % 3600 % 60);
        const hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
        const mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
        const sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
        return hDisplay + mDisplay + sDisplay; 
    }

    connectedCallback(){
        if(window.localStorage.getItem("startTimer")){
            this.setTimer()
        }
    }
}
  1. In stopWatch.js, we are using StartTimerHandler method to generate the latest Date time and storing that timestamp to localstorage with key startTimer
  2. setTimer method gets called on click of the start button which will check if any time is already available in localstorage or not and run the timer which will called every second.
  3. secondToHms convert second to hours and minutes and return the string in the proper readable format.
  4. connectedCallback is used to make sure on tab change and coming back to component checking timer is running or not if yes trigger the setTimer method

stopWatch.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
    </targets>
</LightningComponentBundle>

7. Create stopWatch.css file in the component folder and Add the following style to stopWatch.css file to styling.

stopWatch.CSS

.heading{
    font-size: 30px;
    color: #295646;
    font-weight: 700;
}
.timer{
    font-size: 30px;
    padding:0 1rem;
}

Final Output

Now place your component to the record page. You will see the following output

Fig:1 stopWatch component after pacing on the page

Categorized in:

Recent Posts,

Last Update: January 27, 2024