What is the best way for JavaScript to wait for a click function to finish before repeating the same function when the user clicks again

I have created a simple text-based game using HTML where the player wants to sell their item.

<input name="gg1" id="gg1" value="10">
<a href="javascript:;" onclick="fastbtn(1);">Sale</a>
<script>
  function fastbtn(sid){
  var aa = jQuery("#gg"+sid).val();
  if(aa > 0){
      aa--;
      jQuery("#gg"+sid).attr("value", aa);
      ajaxget('plugin.php?id=game&do=store&submit=true&timestamp=12345&gg1[1]=1&ggqty[1]=1&formhash={FORMHASH}&fastbuy=true','bbb'); //this is my ajax function -> ajaxget(requesturl,return result to id);
  }
</script>

For example, the value = 10, but when the user clicks 10 times quickly (fast clicking), the value turns to 0, but my server-side only processes 8 times.

Is there any way to match the quantity of clicks with the server side?

In my thinking, is it possible for the second click of fastbtn(sid) to wait until the first click of fastbtn(sid)'s ajaxget is completed before processing?

Answer №1

The reason for this issue is when a rapid clicking occurs, multiple ajax network requests are sent before the server has had time to process them, leading to disparities in the response.

To solve this problem, one simple solution is to disable the button while the ajax request is pending. This will ensure that only one active ajax request can be made at any given time.

If you're using an anchor tag where disabling is not possible, you can use a flag like isPending.

  • Initially, set the flag to false to indicate no pending requests.

  • When initiating an ajax request, set the flag to true to show that it is busy handling a request.

  • After the ajax request is completed, reset the flag back to false.

Before processing each click event, check if the flag is set to prevent multiple simultaneous requests.

In case you're using jQuery's get() function for ajax, follow the provided code snippet:

<script>
    var isPending = false;
    function fastbtn(sid, t) {
        if (isPending)
            return;

        var aa = jQuery("#gg"+sid).val();
        if(aa > 0){
            aa--;
            jQuery("#gg"+sid).attr("value", aa);

            ajaxget('plugin.php?id=game&do=store&submit=true&timestamp=12345&gg1[1]=1&ggqty[1]=1&formhash={FORMHASH}&fastbuy=true','bbb');
        }

        //...
        //..
        //.
    }

    function ajaxget(url) {
        isPending = true;
        $.get(url, function(data, status) {
           // <--only fires on success
        })
        .done(function() { // <--only fires on success

        })
        .fail(function() {  // <-- only fires on error

        })
        .always(function() {  // <-- this always fires
            isPending = false; 
        }); 
    }
</script>

Another approach could be to handle the decrement (aa--) inside the ajax success callback or in the done() function so that the value of aa changes only after the server has confirmed and recorded the change.

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 approach for testing a function containing document.querySelector() with unit tests?

export function calculateNavHeight() { const merchantNav = document.getElementById( 'merchant-header-main-wrapper-internal' ) const dw2Nav = document.querySelector('.cw_navbar__mainnav') let navHeight = 72 // Default Nav hei ...

Performing a JQuery Ajax request to post data and maintain current page displayed

How can I ensure that my request remains on the second page after data is posted from the first page? $.ajax({ cache: false, url: base_path + '/second.php', type: 'post', ...

Is there a way to direct URLs with varying "levels" in Express?

I am in the process of learning the MEAN stack and developing a tool within my API that can multiply a series of numbers. I have encountered two questions that the Express Documentation did not address. What is the best way to route URLs of varying depth? ...

What is the procedure for matching paths containing /lang using the express middleware?

I need to target paths that contain /lang? in the URL, but I am unsure how to specifically target paths that begin with /lang? I have two routes: app.get('/lang?..... app.get('/bottle/lang?....... I want to target these routes using app.use(&a ...

Is there a way to convert the value from a radio input into a boolean and save it?

I am looking for a way to store the selected input value as a boolean in the database. Essentially, I want the option to be stored as 1 or 0 in the database once a button is clicked. Is there a way to save true as false? Please note that regardless of yo ...

Concealing tables or forms using Javascript

I need a function to toggle the visibility of an HTML element when clicking on another element. The menu I have includes a submenu with two options - one to display a table and the other a form. Clicking on the first option reveals the table, and then cli ...

JavaScript recursive function to find the sum of array elements that equals to the given target number n

Currently, I am making my way through the Javascript course available on freecodecamp. However, in one of the lessons that cover recursive functions, I have hit a bit of a roadblock. The code snippet that is causing me confusion is as follows: function su ...

Calculate the total amount by multiplying the price and quantity values within nested arrays

I have a collection of objects with nested arrays structured like this [ { orderId: 123, orderStatus: 'Pending', date: 'June 13, 2020', products: [ {product: 'choco', price: 300, qty: 3}, {product: 'm ...

Ways to dynamically assign value to a checkbox using jquery

var sites = sites_str.split(","); $.each(sites,function(i,j) { $('.check').append("<input type=checkbox name=site_name value=sites[i]>"+sites[i] +"</br>" }) I am facing an issue when trying to retrieve the values of selected check ...

Creating a new nested object in JavaScript using the keys of the current object

What is the most efficient method for creating a new object based on the keys of the current object? Each key in the original object should correspond to a specific element in the new object - for example, activityName1 should match the first element' ...

Output the JSON string retrieved from a specified URL

I'm currently working on using ajax to retrieve and parse JSON data from a specific URL. I am looking for assistance on how to store the parsed array into a variable. Any guidance or suggestions would be greatly appreciated. Thank you! function rvOff ...

Is there a way to obtain cookies on a Server-side component in the latest version of Next.js?

import axios from "axios"; const Api = axios.create({ baseURL: "http://127.0.0.1:5000", }); axios.defaults.headers.common["Authorization"] = cookie; In server-side environment, document.cookie is not accessible. Alternat ...

Exploring the process of mapping an array with unidentified object properties

Here is a new way to write it: const array = [ {name: 'John', age: 30} {name: 'Alice', age: 25} {name: 'Bob', age: 40} ] function DisplayComponent({array}) { return ( {array.map(( {name, age} ) => ( <p ...

What exactly is Bootstrap - a CSS framework, a JavaScript framework, or a combination

Being new to Bootstrap, I have taken the time to explore What is Bootstrap? as well as http://getbootstrap.com/. From what I understand so far, Bootstrap is a CSS framework that aids in creating responsive designs that can adapt to various devices. Essent ...

Transferring JavaScript variables to PHP

I am trying to send a JavaScript variable to PHP. Here is the code I am using: function sub(uid){ window.location.href='<?php echo $urlp -> certificationceap(uid) ;?>'; However, I am encountering an issue. ...

Locate the position of a substring within a Uint8Array

I'm working with a Uint8Array that contains the content of a PDF file. My goal is to locate a specific string within this array in order to insert additional content at that particular position. My current approach involves converting the Uint8Array ...

Group by month and calculate the total sum using mongoose in MongoDB

I'm currently working with the orderdetails model in my project. Here is a snippet of the schema: const model = new Schema( { district: { type: String }, category: String, producer: String, variety: String, qty: String, price ...

The 1and1 Server is experiencing a 500 internal error when using Ajax and jQuery .Load() functions, but accessing the URL directly seems to

Currently, I am utilizing a jQuery .load() function to enable infinite scrolling in a CakePHP web application. Below is the snippet of Javascript code: $("#post_container").append('<div class="batch row" style="display:none;"></div>&apos ...

The property 'licenses' has incompatible types. The type 'License[]' cannot be assigned to type 'undefined' in the getServerSideProps function while using iron-session

I am encountering an issue with red squiggly lines appearing on the async keyword in my code: Argument of type '({ req, res }: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => Promise<{ props: { admin: Admin; licenses?: undefined ...

Tips for displaying an error message when entering an incorrect password using Firebase Simple Login email-password authentication

I am utilizing Firebase's Simple Login as an administrator login for a blog-style website. The correct combination of email and password grants write access to the database on Firebase. Following the provided documentation, I have created distinct sec ...