Is it possible to send arguments to a debounced function using _.lodash?

Utilizing _lodash.debounce() has been a bit of a challenge for me. While I have managed to get it working, I can't help but feel that there might be a better way to implement it. The examples provided on the lodash website are quite basic and don't involve passing parameters. Here's the code snippet in question:

$scope.parsePid = _.debounce(function () {
    $scope.$apply(function () {
        var pid = $scope.option.sPidRange;
        if (pid == null || pid === "") {
            $scope.pidLower = null;
            $scope.pidUpper = null;
        }
        else if (pid.indexOf("-") > 0) {
            pid = pid.split("-");
            $scope.pidLower = parseInt(pid[0]);
            $scope.pidUpper = parseInt(pid[1]);
        }
        else {
            $scope.pidLower = parseInt(pid);
            $scope.pidUpper = null;
        }
    });
}, 1500);

The function $scope.parsePid above is debounced. However, I'd like to find a way to pass the parameter rather than retrieving it from $scope.option.SPidRange.

To call the function, I use:

$scope.$watch("option.sPidRange", function (pid) {
    if (pid !== null) {
        $scope.parsePid();
    }
});

In this case, the value of pid should match $scope.parsePid.

I've attempted to pass the pid value into the debounced function directly without success. Is there a way to pass parameters into the debounced function $scope.parsePid()?

Answer №1

UPDATE

It is important to provide an argument for the function like this: _.debounce(function (pid) {

Check out an example using debounce

$scope.parsePid = _.debounce(function(pid){
  $scope.$apply(function(){
    if (pid === null || pid === "") {
      $scope.pidLower = null;
      $scope.pidUpper = null;
    } else if (pid.indexOf("-") > 0) {
      pid = pid.split("-");
      $scope.pidLower = parseInt(pid[0],10);
      $scope.pidUpper = parseInt(pid[1],10);      
    } else {
      $scope.pidLower = parseInt(pid,10);
      $scope.pidUpper = null;
    }      
  });
},1500);

Consider utilizing the built-in $timeout function

View an example with $timeout

var promise;

$scope.parsePid = function(pid){
  $timeout.cancel(promise);
  promise = $timeout(function(){     
    if (pid === null || pid === "") {
      $scope.pidLower = null;
      $scope.pidUpper = null;
    } else if (pid.indexOf("-") > 0) {
      pid = pid.split("-");
      $scope.pidLower = parseInt(pid[0],10);
      $scope.pidUpper = parseInt(pid[1],10);      
    } else {
      $scope.pidLower = parseInt(pid,10);
      $scope.pidUpper = null;
    }
  },1500);
};

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

Is there a way to tally ng-required errors specifically for sets of radio buttons?

Currently, I am working on a form in AngularJS that includes groups of radio buttons. One of my goals is to provide users with an error count for the form. However, I have encountered a peculiar issue: After implementing this code to keep track of errors ...

Avoiding repetitive rendering of child components in ReactJS

In my React project, I have a parent component that contains 3 children components, structured like this: var Parent = React.createClass({ render: function() { return (<div> <C1/> <C2/> <C3/> ...

Managing promise errors by verifying the response

I am currently facing an issue where I need to handle inappropriate responses in the 'then' block of the code snippet below. getData().then(response => transformData(response)); I believe I need to implement something like this, but I am uns ...

What is the best way to thoroughly uninstall Ionic and Cordova from an Ubuntu system?

Is there a way to completely remove Cordova and Ionic 1 and all of their dependencies from my Ubuntu system? And how can I reinstall them again? I found this blog helpful for installing Ionic and its dependencies: I attempted to uninstall Cordova and Ion ...

The Javascript calculation function fails to execute proper calculations

I have been facing immense frustration while working on a project lately. The project involves creating a unique Webpage that can calculate the total cost for users based on their selections of radio buttons and check boxes. Assuming that all other functi ...

What are the steps to start up a NodeJS API using an Angular app.js file?

Currently, I am following various online tutorials to develop a web application using the MEAN stack and utilizing a RESTful API. I have encountered some challenges in integrating both the API server and Angular routes. In my project, I have a server.js f ...

What is the best way to generate an array from JSON data while ensuring that the values are not duplicated?

Upon receiving a JSON response from an API, the structure appears as follows: { "status": "success", "response": [ { "id": 1, "name": "SEA BUSES", "image": null }, { "id": 2, ...

Loading images lazily using knockout.js

I have been working on implementing lazy loading for images using knockoutjs binding. I previously successfully implemented lazy loading without the knockoutjs framework, but I am unsure of how to achieve this with knockoutjs binding. Below is my HTML code ...

The Angular JavaScript page successfully compiles, yet displays only a blank screen

I am facing an issue with my Angular app where it compiles successfully, but the HTML page appears blank and my application is not displaying properly. I have encountered similar problems in the past which were often related to Imports, but this time I&apo ...

How are objects typically created in Node.js applications?

These code snippets are from Node.js tests, and I am curious about why one method of instantiating an object is favored over another? // 1 var events = require('events'); var emitter = new events.EventEmitter(); emitter.on('test', doSo ...

Exploring time differences in Javascript

I am trying to save a JSON AJAX response from the server in the browser's localStorage for a duration of one minute, along with a timestamp generated using new Date().getMinutes(). Upon triggering $(document).ready, I aim to check the stored timestam ...

Having trouble reaching the AngularJS animation class breakpoint for removeClass or addClass operations

Can anyone help me figure out why my animation class isn't triggering in this codepen? I can access the controller methods fine, but the animation class doesn't seem to work properly. Any ideas on what I might be missing? Check out the codepen w ...

Is it possible to manage how many times a functional react component re-renders based on changes in its state?

For my practice e-commerce app, I have a functional component called "Shop" with two states: [products, setProducts] = useState([10ProductObjects]) and [cart, setCart] = useState([]) Upon the initial render, 10 products are loaded and each Product compone ...

How can I transfer a variable from one webpage to another within the MEAN stack?

This is the Angular View Code: <button class="btn btn-primary" ng-click="edit(obj._id)">Edit</button> Here is the Angular Controller code: $scope.edit=function(id) { console.log('edit() called........'); console.log(id); ...

Struggling with using flexboxes and creating animated elements

Seeking assistance with animating the search bar on a website project. The animation is functioning, but the search input abruptly moves when the animation starts, as shown in this GIF: I am utilizing jQuery for the animation because I also want to implem ...

Unleashing the power of jQuery ajax without requiring a server

I've been incorporating jQuery ajax calls on my HTML pages. $.ajax({ url: 'search/' + page + '.html', dataType: 'text', success: function(data) { $(".searchData").html(data); $(".searchData"). ...

Another choice for object-fit:contain workaround for IE

Is there an alternative option to object-fit: contain that is compatible with Internet Explorer? Below is a snippet of my code: .cbs-Item img { height: 132px ! important; width: 132px ! important; object-fit: contain; <div class="cbs-Ite ...

Disable Three.js when WebGL is not supported: Tips and tricks

I read about how to switch to canvasrenderer if webgl is not supported. renderer = Detector.webgl? new THREE.WebGLRenderer(): new THREE.CanvasRenderer(); I'm not sure how to completely remove everything if webgl is not detected. I have an image in t ...

When using JavaScript with React, setting a value after the onBlur event can result in users having to click

In my React form, I have an input button with an onBlur event that sets the value to a useState property. However, after the onBlur event is triggered, the user has to click the button twice to focus on it properly. It seems like the page needs time to pro ...

Detecting button clicks in different views using Backbone.js

In my current setup, I have a main parent view called View.A which is responsible for managing two child views - View.B and View.C. Specifically, View.B contains buttons that trigger events on that view. Configuration View.A View.B view.B.template. ...