Issues with the throttling function of the setTimeout method in an

Having some trouble with my timer and function for retrieving data on button clicks. I'm trying to prevent too many rapid requests.

Here's the code snippet for the timer:

  var timer;

And the function that updates via AJAX:

  function doTheThing(data){
    clearTimeout(timer);
    $.ajax({
        url:'/post/url',
        data:data,
    }).done(function(data){
       timer = setTimeout(function(){
           getMoreData();
       },2000);
    });
   }

The goal is for the timer to reset on each request, preventing multiple simultaneous requests triggered by fast button presses. The getMoreData() function should ideally only fire once even if buttons are pressed rapidly.

   function getMoreData(){
       // Another AJAX request here
   }

But it seems like the timer isn't working as intended. Any ideas on what could be causing this issue?

Answer №1

The reason why your current approach is not effective is due to the fact that you are clearing the timeout within the doTheThing(data) function. Each ajax request has a delay, so if you click quickly, the clearTimeout will be triggered before any setTimeout is set, rendering it ineffective.

It might be beneficial to relocate this action to your getMoreData method, for reference check out this link

function getMoreData(){
   clearTimeout(timer);
   timer = setTimeout(...)
   //Additional ajax calls   
}

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

detect and handle errors when deploying the Node.js function

I'm currently attempting to use code I found on Github to insert data into a Firestore database, but unfortunately, I keep encountering an error. Here's the specific error message: 21:1 error Expected catch() or return promise/catch-or-re ...

How can I link two separate webpages upon submitting a form with a single click?

Here is a snippet of my code: <form action="register.php" method="post"> <input type="text" name="uname"> <input type="submit" > </form> Within the register.php file, there are codes for connecting to a database. I am looking ...

Evolving characteristics of Bootstrap popover

I am currently working on a text field and button setup where I have implemented a popover feature using Bootstrap. This is the code snippet I am using: function displayPopover() { $("#text").popover("show"); } The popover appear ...

Encountering a glitch while attempting to render with the select tag in React.js

I have developed two functions that generate JSX content and created a logic to display each function based on the user's choice: const Register = () =>{ const [value, setMyValue] = useState() function Zeff(){ return( <div> <h1& ...

Tips for establishing optimal parameters for an object's dynamic property

I am working with an array of objects: export const inputsArray: InputAttributes[] = [ { label: 'Name', type: 'text', name: 'name', required: true }, { label: 'User name ...

Issue with draggable div containing gmap not functioning on mobile browsers

Is it possible to make a specific div draggable without dragging the content inside, such as a gmap widget? I have tried implementing this functionality in my code and it works on a computer browser but not on a mobile browser. Here is the simplified versi ...

Obtaining a URL from a parameter

I have a unique situation with one of my parameters in the routing, as it involves an actual URL. router.get('/api/sitemap/:url', function(req, res) { var url = req.params.url; ... } How can I ensure t ...

Challenges with XML parsing in Ajax and jQuery

Encountering an Issue: Add "undefined" for each element. I've spent hours researching solutions to this problem, but have not been able to find a resolution. Apologies if this question has been asked numerous times before. I am attempting to retriev ...

Do you think this architecture is ideal for a NodeJS recursive MongoDB archiver?

Currently, I am faced with the challenge of archiving data stored on a MongoDB server that has been operational for more than a year. The server has accumulated close to 100GB of data, with many collections containing over 10 million documents each. Unfort ...

Handsontable: How to update renderers when a row is deleted

Implementing Handsontable into our reporting system has been a success, except for one issue. I am using renderers to highlight error cells by setting the background color to red. However, when I remove a row using the context menu's "remove row" opti ...

Evaluating the parser for oauth2 implicit grant access_token using javascript

I am currently developing an Angular application that utilizes the implicit grant oauth strategy. In case I do not have a valid access token in my cookies, I am redirected to the web interface of the authentication server where I input my credentials and t ...

What's the best way to maintain the return type of a function as Promise<MyObject[]> when using forEach method?

I am currently working with a function called search, which at the moment is set up to return a type of Promise<MyObject[]>: export function search(args: SearchInput) { return SomeInterface.performSearch(args) .then(xmlRequest =&g ...

What is the best method for serving static files within a nested EJS view directory?

Assuming I have the directory structure below: |--Views/ | --partial/ | --links.ejs | |--assets/ | --css/ | --styles.css | |--server.js Code for links.ejs <link rel="stylesheet" type="text/css" href="css/forms/switches.css"& ...

Allowing access via Access-Control-Allow-Origin for both ajax calls and HttpURLConnection requests

So I was attempting to access a web URL (which I don't have direct access to) that returns a JSON formatted string. Initially, when trying with an AJAX call, I encountered the error "No Access-Control-Allow-Origin' header is present on the reque ...

What is the best method to retrieve the current time in minutes using the Timer component?

I have integrated the react-timer-hook library into my Next.js application to display a timer. The timer is functioning correctly, but I am encountering an issue where I cannot retrieve the current elapsed time in minutes during the handle form event. My g ...

What is the approach of Angular 2 in managing attributes formatted in camelCase?

Recently, I've been dedicating my time to a personal project centered around web components. In this endeavor, I have been exploring the development of my own data binding library. Progress has been made in creating key functionalities akin to those f ...

How to use RegExp to locate the final return statement within a JavaScript code string

Take a look at this code snippet: cont x = 10; function foo() { return x; // ;; end of function ;; // /* here is a some text here too */ } function bar() { return 10 } return foo() + bar(); // ;;done;; // /* yolo yolo */ This string cont ...

Creating a customized bundle with Bootstrap using the Rollup tool

In the official Bootstrap 5 documentation, it mentions that we can import pre-compiled js files from bootstrap/js/dist and create a custom bundle using tools like Webpack or rollup. https://getbootstrap.com/docs/5.0/getting-started/javascript/#individual- ...

To encounter an "undefined" response in the following route of an express application, utilize the next('route') function

const express = require('express') const app = express() app.get('/user/:uid', (req, res, next) => { if (req.params.uid === 'lai9fox') next('route') else next() }, (req, res, next) => { res.send(`<h1& ...

Encountering issues with loading a module in Aurelia

I've encountered a peculiar issue while attempting to load a module using Aurelia. The moment library was successfully loaded for date formatting, but when trying to load the numeral library in the same manner with npm install <module> --save, i ...