Establish the timeout length to match the duration of the login process execution

I want to create a login form that slides back outside the screen when the user successfully logs in. The animation is based on an if statement that checks the authentication state. However, in order for this statement to work correctly, I have to use a $timeout to allow enough time for the login request to be sent and the authentication state to update before running the if statement.

Currently, the $timeout is set to 1000 ms which works fine as long as the request doesn't take longer than that. But sometimes, the request takes longer than expected. How can I adjust the duration dynamically based on the actual time taken by the request? I don't want to make the user wait unnecessarily if the request completes within 1000 ms.

The login process involves sending requests to Firebase API which results in inconsistent response times.

The animation is triggered from a directive that is activated by two separate buttons—one to display the login form and another to confirm the entered information:

forumApp.directive('mySigninSlide', ['sharedInfo', '$timeout',
    function(sharedInfo, $timeout) {
        return {
            restrict: 'A',
            link: function($scope, element, attrs) {

                /**
                 * Display/hide the login form with animation
                 */
                element.on('click', function() {

                    var sidebar = $('#signin-wrapper');

                    if (element.attr('id') === 'confirm-login-btn') {

                        $timeout(function() {

                            if (sharedInfo.getAuthState()) {

                                sidebar.stop().animate({left: '-606px'});
                                sharedInfo.setError('');
                                $scope.isAnimated = true;
                            }
                        //1000 ms is the minimum required time for the login process
                        }, 1000);
                    }
                    else {
                        if ($scope.isAnimated === undefined || 
                            $scope.isAnimated === false) {

                            sidebar.stop().animate({left: '340px'});
                            $scope.isAnimated = true;
                        }
                        else {
                            sidebar.stop().animate({left: '-606px'});
                            $scope.isAnimated = false;
                            sharedInfo.setError('');
                        }
                    }
                });
            }
        };
}]);

Answer №1

To efficiently check for the authentication state, one approach is to implement a rapid verification process instead of relying on a single $timeout call. Here's an example:

function checkState() {
    maxChecks--;
    if (sharedInfo.getAuthState()) {
        sidebar.stop().animate({left: '-606px'});
        sharedInfo.setError('');
        $scope.isAnimated = true;
    } else if (maxChecks) setTimeout(checkState, 100);
};
var maxChecks = 30;
setTimeout(checkState, 500);

This setup entails waiting for half a second before checking for any updates in the authentication state every 0.1 seconds.

While this method may be effective, it might not be the most optimal solution. Exploring asynchronous approaches could lead to a more efficient and streamlined implementation.

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

How can we determine from ASP.NET C# backend whether the user clicked OK or Cancel on the JavaScript confirm box?

Within the C# backend code for a website, I have implemented code that presents users with a confirmation message detailing the data they are about to submit. This message requires human-confirmation that the information displayed is accurate. The challen ...

Angulating Service Testing

I am encountering an issue that I'm not sure how to resolve because I am inexperienced when it comes to testing. Currently, I am testing a service that includes the following code: import { Injectable } from '@angular/core'; import { Endpo ...

Ways to resolve the error "Expected an assignment or function call but found an expression with no-unused-expressions"

Issue : Error in ./src/components/main.js Line 7: No function call or assignment found, only an expression is present (no-unused-expressions) Search for the specific keywords to get more information on each error. import React from 'react'; ...

Utilized JavaScript and CSS class to create a toggleable button

I am attempting to implement a toggle script on a button by using a CSS class. Issue: When I click on button2, it automatically selects button3, which is incorrect. Only one button should be active at a time upon clicking. function togbtn9() { $("#b ...

When using ReactDOM.render, make sure to provide a function as the last optional `callback` argument

I recently started learning React and I encountered the following error message after writing this code: ReactDOM.render Expected the last optional `callback` argument to be a function. `Instead received: Object` This is my code var Stats = Reac ...

In Angular 9, what is the best way to refresh a component's data field in the DOM without having to reinitialize it?

Exploring Angular 9 for the first time and facing a challenge. I have a feature in my application where users can enter a name, submit it via a POST HTTP request to store the name. In another component, there is a sub-header that displays a list of stored ...

Using Javascript in .NET to restrict the number of characters allowed in a textbox during typing and pasting

Consider this situation: I am attempting to display the indication "XY characters left" and restrict characters in a textbox as the user types. However, since I also have multiline textboxes, MaxLength doesn't always suffice (don't worry, I vali ...

Using Reactjs to dynamically create a table from an array

I've recently started using React JS and encountered a challenge with the following JavaScript array: (7) [Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4)] 0: (4) ["050222222", "field", "field", " ...

Tips for passing a false boolean state value back to the parent component in ReactJS

parent.tsx const [modal, setModal] = useState(false); const [detail, setDetail] = useState({}); <confirmation state={setModal(true)} data={detail} /> confirmation return ( <SweetAlert show={state} success title="Confirm ...

Is there a way to send a non-JSON value to an angular.js http.post function?

Struggling to send two parameters using the HTTP POST method in Angular.js. Here is the code I have implemented: Controller var installerApp = angular.module('installerApp', []); installerApp.controller('InstallerCntlr',function($scop ...

"Implementing a conditional statement in JS / JQuery without the need to

I'm interested in finding out if it's possible for a function's conditional statement to display the result whenever the argument is true, without needing to call the function again. Here is an example of such a statement: if($('#a&ap ...

How to efficiently upload multiple files simultaneously in Angular 10 and .NET Core 5 by utilizing a JSON object

I have a JSON object structured like this: Class->Students this is a basic representation of my TypeScript class export class Classroom { Id:number; Name:string; Students:Student[]=[]; } export class Student { Name:string; Age:number; Sex:string; Imag ...

Showing error messages in Angular when a form is submitted and found to be invalid

My form currently displays an error message under each field if left empty or invalid. However, I want to customize the behavior of the submit button when the form is invalid. <form #projectForm="ngForm" (ngSubmit)="onSubmit()"> ...

"Implement a feature in React.js to dynamically hide an element towards the center

I'm attempting to center align my element, similar to this example here. I'm working with react.js and for some reason, the jQuery code provided is not functioning as expected. $('#img-funder-logo').hide('scale', { percent: 0 ...

Angular not executing Jquery script in included HTML files

Underneath is a simple jquery code snippet: $(document).ready(function() { $("h2").click(function(){ alert("Hello world"); }) }); After clicking on any h2 tag in the website, an alert message will display. The code functions properl ...

The battle between ng-include and ui-view for displaying static content

I am using Angular to populate my index.html page in the usual way. Here is an example of how it looks: <body> <nav ng-include="'app/partials/navbar.html'" ng-controller="NavBarController"></nav> <mai ...

Performing addition and subtraction calculations with HTML and Javascript

I need help creating a simple HTML table for adding and subtracting values, with a limit of 10 and a minimum of 0. I have two functions set up, additionalAdd and additionalSub, triggered by the onclick event, but I keep getting an error saying that totalAd ...

Having issues with the fade-in effect of a div in Javascript while using setInterval

I need help with a fading effect for a div containing multiple images. Despite my efforts, the fade-in animation is not working as expected and I'm unsure what's causing the issue. It seems like the interval function may not be getting called at ...

"A TypeError was not caught when attempting to operate on a null value

Currently, I am using AJAX to generate a tabular format on my webpage. Everything was working fine until I encountered the following problem: Snippet of My Code $.each(res,function(index,row){ console.log(row.bookable); //{id: 2, sl ...

Preserving the selected options in a dynamically populated dropdown list after submitting a form using php

I am attempting to preserve form values even after submitting the form. document.getElementById('start_date').value = "<?php echo $_POST['start_date'];?>"; document.getElementById('end_date').value = "<?php echo $_P ...