Deactivate button after a set period of time

Using angularjs, I have a button to create tickets that works with an http request to call a PHP web service. The problem is that the http request has a delay of x seconds, allowing users to click multiple times during this delay resulting in multiple tickets being created but only one actually working. To solve this issue, I need to add a delay to the button itself. However, I am struggling to make this work. Please review the code and note that the solution should be implemented outside of the request. Here is the link to the jsfiddle for reference: jsfiddle

Answer №1

Angular offers a special $timeout service component specifically for this purpose:

$timeout(function() {
    $scope.betDelay=false;
}, 1000);

One key benefit of using the $timeout utility is that it automatically handles dirty model checking, a task that would not be executed when utilizing the standard window.setTimeout() function.

In essence, Angular does not continuously monitor if changes have been made to the $scope; instead, it only checks at critical stages in the lifecycle of a component, and $timeout facilitates your connection with this lifecycle.

Refer to the updated JSFiddle link: http://jsfiddle.net/Lt7aP/862/


Alternatively, you can explicitly instruct the $scope to perform dirty checking through $apply(). For example,

setTimeout(function() {
    $scope.betDelay=false;
    $scope.$apply();
}, 1000);

Check out this demonstration: http://jsfiddle.net/Lt7aP/863/

Answer №2

From what I gather from your message, it seems that the user has the capability to repeatedly click on the login button, resulting in multiple duplicate entries being made as the API does not have enough time to check for existing records due to the rapid succession of hits.

To tackle this issue, we can implement a mechanism to verify if the button has already been clicked. Establish a variable named $scope.isButtonClicked and initialize it as false. Upon each click event, check if it is currently set to false. If it is indeed false, then switch it to true before proceeding with the request.

function LoginController($scope) {
    $scope.isButtonClicked = false;
    $scope.login = function () {
        if ($scope.isButtonClicked === false) {
            $scope.isButtonClicked = true;
            var request = $http({
                dataType: 'json',
                method: "post",
                url: "/xxx.php",
                data: {
                    data1: $scope.data1,
                    data2: $scope.data2
                },
                headers: { 'Content-Type': 'application/json' }
            });
            request.success(function (data) {
                /* I attempted to introduce a delay at the top but encountered issues with its functionality */
            });
        }
    };
}

http://jsfiddle.net/obohxukw/2/

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

Exploring Node JS Express Thread Clarity

Having recently delved into the world of node js, I've familiarized myself with its architecture. I grasp the concept of the event loop, the main thread (V8 engine thread), and the other threads handled by libuv. When the main thread needs to handle ...

What steps do I need to take to implement a unique second factor of authentication using Firebase?

Looking to enhance the security of my application, I aim to offer my users the option to implement a second factor of Authentication. Currently, I am utilizing Firebase for user logins and registrations, which supports a second factor through SMS verificat ...

Prevent any unauthorized modifications to the ID within the URL by implementing appropriate security measures

I am currently developing an application using React and Express. The URL structure is similar to this: /dashboard?matchID=2252309. Users should only have access to this specific URL, and modifying the match ID should not allow them to view the page. Is ...

Is it possible for Masonry to incorporate RTL (Right-To-Left) direction?

Before, Masonry worked perfectly with the Left-To-Right text direction. Now, I need to adjust it for use with Right-To-Left (RTL) languages like Hebrew and Arabic. When I try running Masonry with RTL text direction, the plugin still lays out the grid in a ...

Comparison Between Jquery and Emerging Javascript Frameworks and Libraries such as Angular, Ember, and React

As a ruby on rails developer, my recent foray into learning Angular and React has opened up new possibilities in the world of Javascript technologies. Despite reading comparison posts to gain insight into the reasons behind using different frameworks and l ...

My node.js code is not producing the expected result. Can anyone point out where I may be going wrong?

I've been working on a BMI calculator where I input two numbers, they get calculated on my server, and then the answer is displayed. However, I'm having trouble receiving the output. When I click submit, instead of getting the answer, I see a lis ...

Knockout.js dropdown pre-selection in nested JavaScript objects is functioning smoothly in KO 2x versions, but there seems to be a compatibility issue with KO 3x versions

This is a sample data that will be loaded from the server in JSON format and constructed into the below object graph. It consists of an array of "Choice" objects, each with properties like id, name, stages, & currentStageId. The "stages" property in th ...

Having trouble using functions with dynamically loaded content via AJAX in JQuery

I am facing an issue with my code. I am trying to dynamically fetch some data and display it. I have checked the request using firebug and it seems to be successful, but the problem arises when I try to execute the activeImage() function. The images are no ...

highcharts-ng expands in flexbox without contracting

I've encountered an issue while trying to incorporate a highchart within a flexbox container. The chart expands along with the container without any problems, but it fails to contract when the container size decreases. My current setup involves angul ...

Angular - creating a specialized input field for a unique MatDialogConfig configuration file

I have a unique setup with a custom MaterialDialogConfig file dedicated to handling all of my material dialog components. Here's what the configuration file looks like: import { MatDialogConfig } from "@angular/material"; export class MaterialDialog ...

Tips for Isolating and Manipulating a Single Element in Array.map() with REACT.JS

Is there a way to change the style of a specific element in an array without affecting others when a button is clicked? I've been struggling with this because every time I try, it ends up changing all elements instead of just the one that was clicked. ...

angular not routing properly

I have set up an index.html page where I have included 2 links: <!DOCTYPE html> <html ng-app="test"> <head> <title>My Angular App!</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular. ...

Execute a bash script from a local URL using fetch

I'm curious about converting a curl command into a bash script with input variables using fetch. It works perfectly in the console: curl -s http://localhost:3001/ident.sh | bash /dev/stdin x627306090abab3a6e1400e9345bc60c78a8bef57 2 10194897676576 ...

Issues with Angular route links not functioning correctly when using an Array of objects

After hard coding some routerLinks into my application and witnessing smooth functionality, I decided to explore a different approach: View: <ul class="list navbar-nav"></ul> Ts.file public links = [ { name: "Home&quo ...

Adjusting webpage zoom based on different screen sizes

Hey there, I ran into an issue with my web page design. It looks great on my desktop monitors, but when I checked it on my laptop, things went haywire. Strangely, adjusting the zoom to 67% seemed to fix the problem. Both screens have a resolution of 1920 ...

Passing Variables from Node JS to Pug Template's HTML and JavaScript Sections

Here is a route that sends various variables to a Pug template: items.js route router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeExp ...

Building a time series collection in MongoDB with Node.js

Are there any npm packages available for creating mongodb time series collections using node.js? I did not find any documentation related to this in the mongoose npm package. ...

transferring information from Node.js/MongoDB to the front-end (invisible in the browser)

I am trying to retrieve data from a mongodb database and pass it to the front-end. The function I have written works in the console, where I can see an array containing elements. However, when I try to view it in the browser, it shows undefined. I am worki ...

What is a memory-saving method to clear an object in JavaScript?

I am looking for a way to use the same object repeatedly in JavaScript by emptying it after its purpose is served, without creating a new object each time. In arrays, I usually do arr.length=0 to clear an array instead of assigning it to a new memory locat ...

Ways to retrieve a variable from a separate PHP script without relying on include()

Being new to PHP, I am facing a challenge in trying to achieve a simple task. My goal is to have PHP read data from MySQL and display it on a web interface. In the main script (index.php), I have written code that fetches data from MySQL and stores them in ...