Lodash Debounce failing to properly debounce

Currently, I am attempting to use Lodash to debounce a function but it doesn't seem to be working properly. My issue appears to be different from what others have experienced on both Stack Overflow and Google when using the _.debounce method.

The implementation I have right now is quite simple (written in Angular with CoffeeScript):

  s.search = -> _.debounce( s._makeSearchRequest, 1000 )()

  s._makeSearchRequest = -> console.log("making search request")

In JavaScript, the code looks like this:

  s.search = function() { _.debounce( s._makeSearchRequest, 1000 )() }

  s._makeSearchRequest = function() { console.log("making search request") }

When I type into an input box and quickly enter random characters, "making search request" is printed multiple times per second in the console, indicating that the debouncing isn't happening as expected.

Any suggestions on what might be causing this issue?

Answer №1

_.debounce generates a function that debounces the specified function. The issue with your s.search function is that it calls _.debounce repeatedly every time s.search is invoked, resulting in the creation of a new function each time, negating the debounce effect.

The recommended solution is to eliminate the arrow and extra parentheses, ensuring that s._makeSearchRequest is defined before being accessed:


s._makeSearchRequest = -> console.log("making search request")

s.search = _.debounce( s._makeSearchRequest, 1000 )

Here's an example in JavaScript:

var s;

s = {};

s._makeSearchRequest = function(q) {
  return console.log("making search request: " + q);
};

s.search = _.debounce(s._makeSearchRequest, 1000);

// invoking s.search three times consecutively
s.search(1);
s.search(2);
s.search(3);

// invoking s.search after 500 ms
setTimeout(s.search, 500, 4);

// invoking s.search after 3 seconds
setTimeout(s.search, 3000, 5);

// timer to display the passing of time
var i = 0;
var t = setInterval(function () {
    i += 1;
    console.log(i + " seconds elapsed");
    if (i > 5) { clearInterval(t); }
}, 1000);
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.min.js"></script>

Answer №2

Give this a shot:

The following code snippet demonstrates how to create a debounced search function in JavaScript using Underscore.js:
    
s._makeSearchRequest = function() {
    console.log("Initiating search request");
}

s.search = _.debounce(s._makeSearchRequest, 1000);

Proof of Concept: http://jsfiddle.net/example_user/abc123/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reversing text in mongodb

https://i.sstatic.net/Y61ML.png In my node.js and MongoDB 5 project, I am attempting to retrieve data where the field "TOTAL DUE" has a value other than '$0.00'. I have successfully selected records where "TOTAL DUE" equals '$0.00' usi ...

nested sequential ajax calls

I am attempting to run a couple of functions with ajax calls inside them in sequence. However, I cannot execute them asynchronously as they both start simultaneously. Here is my code: function engine_start() { a1(); a2(); } a1() { $.ajax( ...

Retrieving the value of an array from a JSON data structure

I am working with the object shown below to extract the desired output. The result will be a new object that represents the final output. var data = { Customer: { Name: "emp1", Departments: [ {Departme ...

Getting rid of items and bringing them back

In my current three.js project, I have implemented a feature that allows users to switch between scenes containing various mesh objects. All objects are loaded simultaneously when the page loads, but the performance is affected by the textures on these obj ...

Exploring the array mapping technique in React with nested objects

As part of a school project, I am working on creating a dashboard to visualize some data. I have successfully loaded the data into the front end using React. Now my goal is to retrieve specific values from a large array. However, I am uncertain about how ...

The issue with the jQuery Mobile onclick event is that it fails to remove the ui-disabled

Ever since I delved into coding with jQuery Mobile, I've noticed a change in the function that once effortlessly removed the "ui-disabled" class. Now, all it does is display an alert message... Snippet from the HTML code: <div data-role="navbar ...

Press the button using the spacebar

I am facing an issue where I have a button with an anchor element that I need to trigger with the spacebar key for accessibility purposes. However, instead of triggering the button, pressing the spacebar causes the page to jump down when the button is in f ...

Issue encountered when attempting to utilize Next-Auth alongside Credentials Provider to authenticate within a pre-existing system

I am currently utilizing the Next-Auth Credentials provider for authentication purposes through our existing API. Following the guidelines provided at https://next-auth.js.org/configuration/callbacks the code snippet used is as follows: callbacks: { ...

"Facing an issue with angular's $http post method as it fails to transmit

Attempting to use $http post in Angular to send an object to a REST service. The data is a JSON object that needs to be passed as a parameter for the method in the service. Here is my Angular code (which is not working for me): $http({ method:'P ...

Are there any straightforward methods to fully freeze an object along with all its descendants in JavaScript (Deep Freeze)?

Often when passing an object as a parameter, functions may access the object by reference and make changes to the original object. This can sometimes lead to unwanted outcomes. Is there a way to ensure that an object remains unchanged? I am aware of the Ob ...

Assigning a variable within a parent function from a child function in JavaScript

Struggling to assign the value of "result" in the inner function. Any suggestions on how to do this? I am able to console log the result variable inside the function, but a friend recommended using promises. However, I have no clue how to implement that ...

Adjust image size based on the size of the screen

I am facing an issue with two images that are created for a 1024 x 768 resolution but I need to use them in a higher resolution. The challenge is to align these two images so that the circle from the first image falls between the second image. Although I ...

an all-encompassing loading animation designed specifically for updates to location.href

We have a situation where a customer's website is displaying extremely slowly within an iFrame, taking about 7 seconds to load. All we can do is provide the customer with a JavaScript file for inclusion on their site, as they are not willing to make a ...

Begin the process of setting up PDF.js on the website

I've been attempting to incorporate PDF.js into my website, but I'm struggling to do it correctly. When I try to display the PDF file on the screen, I encounter this issue: https://i.sstatic.net/aixrP.png Although I can't see the PDF file ...

Does the functionality of Protractor rely on a specific version of AngularJS?

Recently, I began exploring the world of Protractor. One burning question on my mind is its limitations and whether it relies heavily on a specific version of AngularJS. ...

Tips for Choosing the Right Objects in Vue.js

I have the following code that combines all objects in a person and stores them in an array called Cash:[] this.cash = person.userinvoice.concat(person.usercashfloat) Inside person.usercashfloat, there is an element called validate which sometimes equals ...

What steps should I take to modify the date format to "dd / mm / yy"?

When using 'toISOString ()' in JavaScript, it appears as shown in photo 2. How can I modify this format? Note: I am working with AngularJs. Image 1 is located in list.component.ts Additional documents: Image 1 Image 2 Image 1: formatDate(e) ...

Saving numerous files with Promises

There is a Node URL (created using Express) that enables users to download static images of addresses. The calling application sends a request to the /download URL with multiple addresses in JSON format. The download service then calls Google Maps to save ...

I possess a pair of UI tabs. Whenever a button located outside the tab is clicked, I am required to activate a distinct tab

As a beginner in Javascript, I recently encountered an issue with a UI tab element that contains two tabs. My goal is to create a button that, when clicked, will scroll up and activate the second tab. <style> .tab-container { overflow-x: ...

Is there a way to generate an array from 1 to X without using a loop?

What is a way to generate a JavaScript array from 1 to X without using a loop when the value of X is only known at runtime? var arr = []; for (var i = 1; i <= x; i++) { arr.push(i); } ...