Contact us

6545 Market Ave N Ste 100 Canton, OH 44721

Email us

Contact@trailheadiq.com

Contact us

6545 Market Ave N Ste 100 Canton, OH 44721

Email us

Contact@trailheadiq.com

Blog Details

Understanding Throttling in Lightning Web Components (LWC)

What is Throttling?
Throttling is a technique used to control the frequency of function execution. It ensures that a function is not called too often, which can help improve performance and prevent overwhelming system resources.
Why Use Throttling in LWC?
In Lightning Web Components (LWC), throttling is particularly useful for handling events that can fire multiple times in quick succession, such as scroll or resize events. By throttling these events, you can improve the performance of your application by reducing the number of times the function is called.
Explanation:
A throttle function limits the rate at which a specified function can be executed. If the function is called repeatedly, it ensures that the actual function execution happens at most once every specified interval, such as 200 milliseconds.
Benefits of Throttling:
  • Improved Performance: Reduces the number of function calls, especially during high-frequency events like scrolling and resizing.
  • Resource Management: Prevents overwhelming system resources, ensuring a smoother user experience.
  • Enhanced User Experience: By limiting function execution, you avoid janky and unresponsive UI updates.
Implementing throttling in your LWC components helps you build more efficient, responsive, and user-friendly Salesforce applications. 🚀
Utility Code
Let’s start with a utility function for throttling. Create a file named utility.js in the lwc folder.
utility.js

// utility.js
export function throttle(func, limit) {
    let lastFunc;
    let lastRan;
    return function() {
        const context = this;
        const args = arguments;
        if (!lastRan) {
            func.apply(context, args);
            lastRan = Date.now();
        } else {
            clearTimeout(lastFunc);
            lastFunc = setTimeout(function() {
                if ((Date.now() - lastRan) >= limit) {
                    func.apply(context, args);
                    lastRan = Date.now();
                }
            }, limit - (Date.now() - lastRan));
        }
    };
}

Throttling Example
Now, let’s see how to use this utility function in an LWC component. We will create a simple component that throttles the click event on a div element.
functionCallComponent.html

<template>
    <div class="my-div" style="width:200px; height:200px; background-color:lightgray;">
        Click me repeatedly!
    </div>
</template>

functionCallComponent.js

import { LightningElement } from 'lwc';
import { throttle } from 'c/utility';

export default class FunctionCallComponent extends LightningElement {
    renderedCallback() {
        this.template.querySelector('.my-div')
            .addEventListener('click', throttle(this.handleFunctionCall, 200));
    }

    handleFunctionCall() {
        console.log('Function Called');
    }
}

In this example:
  • The renderedCallback lifecycle hook is used to add an event listener to the .my-div element.
  • The throttle utility function is used to throttle the handleFunctionCall method, ensuring it is called at most once every 200 milliseconds.
Detailed Explanation of the Utility Code
throttle Function
The throttle function takes two arguments:
  1. func: The function to be throttled.
  2. limit: The time interval in milliseconds to control the frequency of function execution.
Here’s a breakdown of the throttle function:
  • lastFunc: A variable to store the timeout.
  • lastRan: A variable to store the last execution timestamp.
The returned function uses:
  • context: The this value to be used inside the throttled function.
  • args: The arguments to be passed to the throttled function.
Logic:
  • If lastRan is not set, the function is executed immediately, and lastRan is set to the current timestamp.
  • If lastRan is set, the function execution is delayed using setTimeout. The timeout duration is calculated based on the difference between the current time and the last execution time.
Conclusion
Throttling is a powerful technique for improving the performance and user experience of your LWC applications. By implementing a simple throttle utility function and using it in your components, you can ensure that high-frequency events are handled efficiently without overwhelming the system resources. Feel free to experiment with the throttle function and apply it to different events and components in your Salesforce applications to see the performance improvements firsthand!