Salesforce Lightning: Countdown timer

Today we will have a look at how to create a lightning component for countdown timer which can be used on pages where an operation needs to be completed within a specific time period. Example, an online exam or a banking transaction which expires after a specific time period.

The component contains a datetime field which represents the end time. Once the user selects the date and time and clicks on Start Timer button, the countdown timer will start. Below is the lightning component:

CountdownTimer.cmp
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
 
    <aura:attribute name="endTime" type="String"/>
 
    <aura:attribute name="timeLeft" type="String"/>
 
    <lightning:tile label="Time Left" class="slds-page-header">
        {!v.timeLeft}
    </lightning:tile>

    <lightning:input type="datetime" name="input1" label="Enter a date/time value" value="{!v.endTime}"/>
 
    <lightning:button variant="brand" label="Start Timer" title="Start Timer" onclick="{!c.startTimer}" />

</aura:component>

CountDownTimerController.js
({
    startTimer : function(component, event, helper) {
        var countDownDate = new Date(component.get("v.endTime"));

        // Update the count down every 1 second
        var timer = setInterval(function() {
         
            // Get todays date and time
            var now = new Date().getTime();
         
            // Find the distance between now and the count down date
            var distance = countDownDate - now;
         
            // Time calculations for days, hours, minutes and seconds
            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);
         
            // Display the result in the element with id="demo"
            var timeLeft =  hours + "h " + minutes + "m " + seconds + "s ";
            component.set("v.timeLeft", timeLeft);
        }, 1000);
    }
})

Comments

  1. Would it be possible to set the value of endTime using the datetime value of a field on the case record page, such as an SLA target deadline, and if so, how would you call and pass the field value to the function when the page loads?

    ReplyDelete
  2. Yes, add an init handler and query the field value in apex and return back to your aura component.

    ReplyDelete
  3. Do you have a version that can run on Experience Cloud? and Can it be customized with color, font and size?

    ReplyDelete

Post a Comment

Popular posts from this blog

Salesforce Hacks: System.LimitException: Too many queueable jobs added to the queue: 2

Building an Org Role Hierarchy component in LWC