Timing Events setTimeout vs setInterval in Lightning Web Component Salesforce | LWC Stack ☁️⚡️

 If you ever had a requirement to perform an event after a specific time span or maybe call an event continuously after a specific time span so this blog is for you.

In this blog I will show you how you can use timing events in Lightning Web Components and how to stop them.

A simple scenario to use it in LWC could be if you want to refresh your datatable continuously after 10-20 seconds just to check if there are any change in data in the database.

There are two timing events you can use in your Lightning Web Component.

1. setTimeout(function,milliseconds)

Executes a function after waiting a specified number of milliseconds.

2. setInterval(function, milliseconds)

Same as setTimeout() but repeats the execution of the function continuously.

Example 1: In below example I have used both function to trigger a functionality after a specified number of milliseconds once and continuously, also I have used a button to stop these timeouts.

TimingEvents.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<template>
  <lightning-card title="Timing Events in LWC" icon-name="utility:user">
    <div class="slds-var-m-around_medium">
      There are two timing events in this page. First one will trigger only once
      after a spacific time span and the other one will trigger continuously
      after a spacific time span.
      <br /><br />
      <lightning-button
        variant="brand"
        label="Stop Timing Events"
        onclick={handleStop}
      ></lightning-button>
    </div>
  </lightning-card>
</template>


TimingEvents.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { LightningElement } from "lwc";
import { ShowToastEvent } from "lightning/platformShowToastEvent";

export default class TimingEvents extends LightningElement {
  timeSpan = 5000;
  event1;
  event2;
  connectedCallback() {
    this.triggerEventOnce();
    this.triggerEventContinuously();
  }
  triggerEventOnce() {
    let message =
      "I will trigger only once after " + this.timeSpan + " milliseconds.";
    this.event1 = setTimeout(() => {
      this.customMessage(message);
    }, this.timeSpan);
  }
  triggerEventContinuously() {
    let message =
      "I will trigger again after " + this.timeSpan + " milliseconds.";
    this.event2 = setInterval(() => {
      this.customMessage(message);
    }, this.timeSpan);
  }
  customMessage(customMessage) {
    this.dispatchEvent(
      new ShowToastEvent({
        title: "Notification",
        message: customMessage,
        variant: "success"
      })
    );
  }
  handleStop() {
    console.log("🚀 ~ handleStop");
    this.dispatchEvent(
      new ShowToastEvent({
        title: "Stopping Timing Events",
        message: "Timing events has been stopped!",
        variant: "success"
      })
    );
    clearTimeout(this.event1);
    clearInterval(this.event2);
  }
}


Example 2: In below example I am refreshing records after 5 seconds continuously to check if there are any change in data.

DeleteAccounts.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template>
  <lightning-card title="Delete Records" icon-name="utility:user">
    <template if:true={accounts}>
      <div class="slds-var-m-around_medium">
        <template for:each={accounts} for:item="acc">
          <lightning-layout key={acc.Id} class="slds-var-m-vertical_x-small">
            <lightning-layout-item size="10">
              {acc.Name}
            </lightning-layout-item>
            <lightning-layout-item size="2">
              <lightning-button-icon
                class="makeItTransparent"
                icon-name="utility:delete"
                onclick={deleteAccount}
                data-recordid={acc.Id}
              >
              </lightning-button-icon>
            </lightning-layout-item>
          </lightning-layout>
        </template>
      </div>
    </template>
  </lightning-card>
</template>


DeleteAccounts.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { LightningElement, wire } from "lwc";
import { ShowToastEvent } from "lightning/platformShowToastEvent";
import { refreshApex } from "@salesforce/apex";
import { deleteRecord } from "lightning/uiRecordApi";
import getAccountList from "@salesforce/apex/AccountController.getAccList";

export default class DeleteAccounts extends LightningElement {
  accounts;
  error;
  wiredAccountsResult;
  event2;

  @wire(getAccountList)
  wiredAccounts(result) {
    this.wiredAccountsResult = result;
    if (result.data) {
      this.accounts = result.data;
      this.error = undefined;
    } else if (result.error) {
      this.error = result.error;
      this.accounts = undefined;
    }
  }

  connectedCallback() {
    this.event2 = setInterval(() => {
      refreshApex(this.wiredAccountsResult);
    }, 5000);
  }

  disconnectedCallback() {
    clearInterval(this.event2);
  }
  deleteAccount(event) {
    const recordId = event.target.dataset.recordid;
    deleteRecord(recordId)
      .then(() => {
        this.dispatchEvent(
          new ShowToastEvent({
            title: "Success",
            message: "Account Deleted",
            variant: "success"
          })
        );
        return refreshApex(this.wiredAccountsResult);
      })
      .catch((error) => {
        this.dispatchEvent(
          new ShowToastEvent({
            title: "Error",
            message: "Error Deleting record",
            variant: "error"
          })
        );
      });
  }
}


Output



Checkout complete video tutorial below

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

5 Comments

  1. How this disconnected call back will work. If you can explain that little bit, will be great help for me.

    ReplyDelete
    Replies
    1. disconnectedCallback will work when the component gets removed from the DOM. i.e if you will hide the component using template on button's click.
      Use disconnectedCallback() to clean up work done in the connectedCallback(), like purging caches or removing event listeners.

      Delete
  2. @Kapil, can you tell me how are you able to use async events i.e setTimeout() & setInterval() in connectedCallBack(). Getting an error like 'Restricted async operation' in lwc.

    ReplyDelete
    Replies
    1. Hey checkout solution in below thread
      https://salesforce.stackexchange.com/questions/261416/restricted-async-operation-settimeout-in-lwc

      Delete
  3. This comment has been removed by a blog administrator.

    ReplyDelete