Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Debouncing a Resize Event Handler:
4.2.
JavaScript
4.3.
Search Input Debouncing:
4.4.
JavaScript
4.5.
Debouncing with Leading and Trailing Calls:
4.6.
JavaScript
4.7.
Throttling Scroll Events:
4.8.
JavaScript
5.
Frequently Asked Questions 
5.1.
What is the difference between debouncing and throttling?
5.2.
Can the debounce delay be updated after creation?
5.3.
Is _.debounce() suitable for handling all types of events?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.debounce() Method

Author Pallavi singh
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

In modern web development, managing the rate at which a function can be invoked, especially in response to events like scrolling, resizing, or typing, is crucial for performance and user experience. Lodash addresses this need with the _.debounce() method. This function creates a debounced version of a function that delays its invocation until after a specified time has elapsed since the last time it was invoked. 

Lodash _.debounce() Method

This article will delve into the _.debounce() method, its applications, syntax, and use cases, supported by examples and FAQs.

Why This Function is Used

The _.debounce() function is used to control the rate at which a function is executed, particularly in response to high-frequency events. This is crucial in scenarios like search input handling, window resizing, or scroll events, where the unthrottled execution of a function can lead to performance issues or unnecessary resource utilization. Debouncing ensures that the function is triggered less frequently, improving efficiency and responsiveness.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax, Parameter and Return Value

Syntax: 

_.debounce(func, [wait=0], [options={}])

Parameters:

  • func (Function): The function to debounce.
     
  • [wait=0] (number): The number of milliseconds to delay.
     
  • [options={}] (Object): The options object.
     
  • leading (boolean): Specify invoking on the leading edge of the timeout.
     
  • trailing (boolean): Specify invoking on the trailing edge of the timeout.

Return Value: 

(Function) - Returns the new debounced function.

Examples 

Debouncing a Resize Event Handler:

  • JavaScript

JavaScript

var _ = require('lodash');

function resizeHandler() {

 console.log('Window resized');

}

var debouncedResize = _.debounce(resizeHandler, 200);

window.addEventListener('resize', debouncedResize);

 

// Function 'resizeHandler' will be called after 200ms of the last resize event.

Demonstrates debouncing a window resize event handler.

Search Input Debouncing:

  • JavaScript

JavaScript

function searchDatabase(query) {

 console.log('Searching for:', query);

}

var debouncedSearch = _.debounce(searchDatabase, 300);

// Assuming an input field for search

document.getElementById('searchInput').addEventListener('input', event => {

 debouncedSearch(event.target.value);

});


// Search function will be called 300ms after the user stops typing.

Shows debouncing a search function to reduce the frequency of search operations.

Debouncing with Leading and Trailing Calls:

  • JavaScript

JavaScript

var saveInput = _.debounce(function(text) {

 console.log('Saving data:', text);

}, 1000, { 'leading': true, 'trailing': false });

saveInput('First');

saveInput('Second');

Output immediately: 

'Saving data: First'


// Subsequent calls within 1000ms are ignored.

An example of debouncing a function to trigger on the leading edge.

Throttling Scroll Events:

  • JavaScript

JavaScript

function onScroll() {

 console.log('Scrolled!');

}

var debouncedOnScroll = _.debounce(onScroll, 150);

window.addEventListener('scroll', debouncedOnScroll);


// Function 'onScroll' will be called 150ms after the last scroll event.

Demonstrates using debounce to efficiently handle scroll events.

Frequently Asked Questions 

What is the difference between debouncing and throttling?

Debouncing delays a function call until a certain amount of time has passed without it being called again, while throttling limits the function calls to a certain rate.

Can the debounce delay be updated after creation?

Once a debounced function is created, its delay time is fixed. To change the delay, you need to create a new debounced function with the desired delay.

Is _.debounce() suitable for handling all types of events?

_.debounce() is ideal for events that fire frequently and do not require immediate action for every occurrence, like resize, scroll, or input events.

Conclusion

Lodash's _.debounce() method is an essential tool in event-driven programming, especially for optimizing performance and user experience in scenarios involving frequent event triggering. It allows for effective rate control of function execution, ensuring responsiveness without compromising on functionality.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Lodash _.snakeCase() Method
Next article
Lodash _.gt() Method
Live masterclass