Tips for minimizing database queries for each data type

I'm currently developing an App that requires the user to input numbers into two different fields. The first field is for entering numbers, while the second field displays a calculation based on the input. Each time the user enters a number, a call to the database is made, and I'd like to minimize these calls. Ideally, I want to give the user some time to enter the input before making the database call.

Below is the function defined in a service:

applyStraightRisk = function(slip, amount) {
      applyStraightRiskWin({
        wagerType: '1',
        riskOrWin: 'RISK',
        riskValue: amount,
        winValue: slip.win || 0,
        amount: amount,
        selections: [slip]
      });
    }, applyStraightWin = function(slip, amount) {
      applyStraightRiskWin({
        wagerType: '1',
        riskOrWin: 'WIN',
        riskValue: slip.risk,
        winValue: amount,
        amount: amount,
        selections: [slip]
      });
    }

return {
  riskWinCalculations: function(params, scope, index) {
    switch (params.type) {
      case 'RISKSTRAIGHT':
        applyStraightRisk(params.slip, params.slip.risk);
        break;
      case 'WINSTRAIGHT':
        applyStraightWin(params.slip, params.slip.win);
        break;
  };
}

One option I was considering was using $timeout/setTimeout but I wonder if there is a more effective approach?

Answer №1

If you want to add a delay to your function, you can utilize the 'debounce' feature from the underscore.js library.

    applyDelayedFunction = _.debounce(function(param1, param2) {
    ...
    }, 500); // Function will only run once every 500 milliseconds

If you prefer to use this function independently (source: underscore.js)

_.debounce = function(func, wait, immediate) {
  var timeout, args, context, timestamp, result;

  var later = function() {
    var last = _.now() - timestamp;

    if (last < wait && last >= 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function() {
    context = this;
    args = arguments;
    timestamp = _.now();
    var callNow = immediate && !timeout;
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
};

This method involves using setTimeout for timing control.

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

What is the best way to halt a specific function in jQuery?

I recently developed a website for my photographer friend, and I implemented a feature where the home page is initially blurred. Visitors can click a button to unblur the content. While the functionality works smoothly, there's one issue - every time ...

How can I add color to arrow icons in tabulator group rows?

Is there a way to specify the color of the arrows in collapsed/expanded group rows? Also, what CSS code should I use to define the font color for column group summaries? You can view an example of what I am trying to customize here: https://jsfiddle.net/s ...

When transitioning to an object, Vue.js fails to refresh

My component contains an object called elements: elements: { id: { text: '', color: '', ... } To modify it, I use: <a-textarea autoFocus placeholder="text to include" :style="{ width: &ap ...

Assign a unique HTML attribute to a child element within a Material-UI component

Currently, I am trying to include the custom HTML5 attribute "data-metrics" in the span element within the ListItemText Material UI component. However, I am facing some difficulty achieving this as per the specifications outlined in the Component API Docum ...

Adding Node Modules during the setup of an ElectronJS application

Hey there! I'm currently working on an ElectronJS application designed for developers. One of the key features is checking for the presence of NodeJS on the user's computer. If it's not detected, the app will automatically download and insta ...

Obtain every possible sequence of US phone number segments for a provided number

The format of a US phone number is as follows: (XXX) XXX-XXXX Given a string consisting only of digits with a length between 0 and 10, I want to generate an array of all possible chunks that match the US phone number format. For example: Input: "54" Out ...

Executing actions on events in a Basic jQuery sliderLearn how to handle events and execute

I utilized the slider from the bjqs plugin at after reviewing the documentation, I noticed it only offers options and lacks events/functions. I am referring to events/functions like onSlideChange and onSlideDisplay. While other plugins such as bxslid ...

Is there a way to utilize the 'interval' Rxjs function without triggering the Change Detection routine?

My goal is to display the live server time in my application. To achieve this, I created a component that utilizes the RXJS 'interval' function to update the time every second. However, this approach triggers the Change Detection routine every se ...

The download functionality in HTML5 is not functioning properly, so users are forced to rename files when downloading

For weeks, I've been struggling to change the name of the downloaded file. Despite my efforts, instead of being named Chrysanthemum.jpg, it ends up as a hash of the file like 241693260.jpg In my backend setup, I utilize Node.js and Express.js for man ...

Background image not displaying in new tab after Chrome extension installation

I have been developing a Chrome extension that alters the background image of a new tab. However, I have encountered an issue where the background image doesn't change the first time the extension is loaded. This problem has also occurred very occasi ...

Looking to add some movement to your website? Learn how to make an image track your mouse pointer in a specific section of your webpage

I'm just starting out with web design and javascript, so please be patient. My goal is to have an image follow the mouse pointer only when it's within a specific section of my website. I've managed to make the image track the mouse cursor ...

Tips for extracting unique values from two arrays and returning them in a new array using JavaScript

Hello, I need assistance with combining two arrays. Array a contains [1,2,3] and array b contains [2,5]. I would like the result array to only include elements that are unique between the two arrays, such as [5]. Can you please provide guidance on how to ...

When was Chrome first updated to include timezone offset support for Intl.DateTimeFormat()?

My experience with Chromium 121 has been positive using the Intl.DateTimeFormat as shown below: new Intl.DateTimeFormat('en', { dateStyle: 'long', timeStyle: 'long', timeZone: '+0500', }).format ...

When using React.js with Leaflet, ensure that the useEffect hook is only run on Mount when in the

I have encountered an issue where I need to ensure that the useEffect Hook in React runs only once. This is mainly because I am initializing a leaflet.js map that should not be initialized more than once. However, anytime I make changes to the component&a ...

Duplicate values of React object properties when using .push method within a loop

In my code, I've implemented a function called handleCreate that is responsible for taking user data and inserting it into a database. Within the loop of aliasArr.forEach(), I am sending new user instances to my database for each element in the alias ...

Creating a private variable to perform a select_sum query

I have defined private variables in my CodeIgniter code like this: private $table = 'phone'; private $column_order = array(null, 'name', 'price'); private $type = array('type'); private $battery_consumption = array ...

Is there a way to postpone the execution of a scheduled interval function?

Below is the setup of my function: setInterval(function () { get_fb(); }, 10000); If a user interacts with an element, such as hovering over it or clicking on it, I want to reset the timer back to 10 seconds. How can I instruct the program to achieve th ...

Calculating remaining change with the modulus operator in JavaScript

I have a task where I need to convert any given number of pennies into the correct amount of Quarters, Dimes, Nickels, and leftover pennies. My program currently uses Math.floor() to calculate the total value of each respective coin type when executed in ...

Stop the execution of javascript code based on the screen width

On my website, I have two menus located in different sections of the page. One menu is shown when the screen width is greater than 555px, while the other menu appears when the screen width is less than or equal to 555px. Although the menus are essentially ...

Prevent text from wrapping when using jQuery to animate font size

I have a unique way of showcasing content in a preview format by utilizing em units for scaling and adjusting the root font size to increase or decrease. When users click on the preview, the full content is revealed with an animation that scales the font s ...