Nested SetTimeout function fails to execute

Attempting to implement a button that provides feedback for its actions, I am faced with a challenge in Angular. After sending a put request to the server, the button's state changes to show this action. Upon receiving a response, the button's state is updated again to indicate success or failure for 1.5 seconds before returning to its original state. Additionally, a message displays the outcome and after 5 seconds, an additional action should occur - hiding the message on failure or redirecting the page on success. It is this final step that is proving difficult.

My query revolves around whether it is possible to nest a setTimeout inside another setTimeout.

This is the code snippet within the button function:

$scope.resetPassword = function() {

    $scope.ShowSuccessMessage = false;
    $scope.ShowFailedMessage = false;

    var querystring = $location.search();

    var dataObject = { email1 : $scope.formEmail1, email2 : $scope.formEmail2, password1: $scope.formPassword1, password2: $scope.formPassword2, token: querystring.token };

    var responsePromise = $http.put("/myurl/", dataObject, {});

    //  change colour and icon of reset button for 1.5 sec
    var $el           = $("#resetPassword");
    var resetButton   = 1500;
    var resetMessage  = 5000;
    var originalColor = $el.css("background");
    var originalIcon  = $el[0].firstChild.className; 

    $el[0].firstChild.className = "fa fa-circle-o-notch fa-spin";

    responsePromise.success(function(dataFromServer, status, headers, config) {
      $el.css("background", "#02c66c");
      $el[0].firstChild.className = "fa fa-check-circle";

      $scope.ShowSuccessMessage = true;

      ResetButton($el, $scope, originalColor, originalIcon, resetButton, true, resetMessage);
    });

    responsePromise.error(function(dataFromServer, status, headers, config) {
      $el.css("background", "#d9534f");
      $el[0].firstChild.className = "fa fa-times-circle";

      $scope.ShowFailedMessage = true;

      ResetButton($el, $scope, originalColor, originalIcon, resetButton, false, resetMessage);
    });
};

ResetButton = function(el, scope, originalColor, originalIcon, resetButton, success, resetMessage)
{
  setTimeout(function() {
    el.css("background", originalColor);
    el[0].firstChild.className = originalIcon;

    ChangeMessageOrChangeLocation(scope, success, resetMessage);
  }, resetButton);
}

ChangeMessageOrChangeLocation = function(scope, success, resetMessage)
{
  if(success) {
    setTimeout(function(){
      window.location = '/signin';
    }, resetMessage);
  }
  else {  
    setTimeout(function() {
      scope.ShowFailedMessage = false;
    }, resetMessage);
  }
}

Edit: Check out the live example Greedy Magpie (Note: Work in progress, not all features may be functional.) Simply click on the change password button...

Answer №1

When using winfow.setTimeout, the Angular digest cycle is bypassed causing the view not to update. To solve this issue, you can either include scope.$apply() after scope.ShowFailedMessage = false;, or switch to using $timeout service instead of setTimeout. The latter option is recommended for better performance.

For more information on the $timeout service, refer to the documentation here: $timeout

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

Fading away backdrop images for the header

I've created a header class in my CSS with the following styling- header { background-image: url('../img/header-bg.jpg'); background-repeat: none; background-attachment: scroll; background-position: center center; .backg ...

Implementation of asynchronous code in event handlers is necessary

In my AngularJS controller, I have implemented an event mechanism to communicate with external elements. One particular event is triggered to retrieve the URL where the data should be sent. The event handler reacts to this event by making an AJAX call usi ...

Enhance the material-table component by incorporating dynamic information into the lookup property

I am currently facing challenges while attempting to dynamically add data to the lookup property in the Material-Table component. The lookup is structured as an object, and you can refer to its definition in the initial example provided here. However, it ...

I am having difficulty accessing specific data in JSON using Searchkit's RefinementListFilter

Utilizing searchkit for a website, I am encountering issues accessing previously converted data in json format. The structure of my json directory is as follows: (...) hits: 0: _index: content _type: content _source: ...

Retrieving and storing state in session storage with React

My webpage features a sidenav with expansion panels that can be opened and closed. I am currently working on setting the state to keep track of which expansion panel is open. However, when I click on one of the items in the sidenav, I get redirected to a ...

Is it possible for CSS to prevent the insertion of spaces?

When filling out a form, I am able to insert spaces in inputs but not in the textarea (which is necessary). Interestingly, inserting spaces in the textarea works flawlessly. <form action="/#wpcf7-f519-o1" method="post" class="wpcf7-form" enctype="mu ...

Determine the quantity of items that meet specific criteria

The initial state of my store is set as follows: let initialState = { items: [], itemsCount: 0, completedCount: 0 }; Whenever I dispatch an action with the type ADD_ITEM, a new item gets added to the items array while also incrementing the count in ...

Having difficulty getting a basic code to work: ajax method ($.post) with MySQL is not

I am facing an issue with this code not functioning properly. I want to display the result of a MySQL query without sending any data using my simple Ajax code. $('.myClass').on('click',function(){ $.post('resultAll.php'); ...

Error encountered while assigning a source to images

I am new to AngularJS and I just started using it yesterday for the first time (and loving it!). Please forgive me if this is a basic question. I have been looping through a dataset named "leagues" and mapping my HTML template without any issues. The data ...

Unable to revert input to its previous state after setting the value attribute in ReactJS

It may seem strange, but I set the value attribute of the input tag to a random state. However, I am unable to type anything into the input field. The input field is meant to be cleared after clicking, but unfortunately, nothing happens. (I apologize if ...

React Native: Why is useState setter not causing a re-render?

As a beginner in react and javascript, I am facing an issue with showing an ActivityIndicator while logging in a user. The setIsLoading method doesn't seem to change the state and trigger a rerender. When the handleLogin method is called on a button c ...

Experiencing an Internal Server Error while attempting to upload a product using AngularJS in the MEAN Stack

I'm currently struggling with an Internal Server error while trying to add a product through the http service ($http.post) in AngularJS. To provide you with the necessary details for assistance, here are the key files involved: **index.js : This file ...

Implement a dropdown menu for filtering, but it is currently not functioning as expected

When I select a city_name, my goal is for the graph to only display information pertaining to that particular city. In the params section of my code, I have included filtering options using a selection menu in Vega-Lite. However, despite selecting Brisba ...

Focus on a particular div in order to enable scrolling beyond its boundaries

Whenever I move my mouse over the div tag, I am able to scroll the content. However, if I move the mouse outside of the div box, scrolling stops. Is there a way to make the specific div element track the mouse pointer no matter where it goes? <div st ...

Guide to setting up Firebase pagination in a NextJS 13 server component

Currently, I am working on developing a product page that showcases all products and functions as a server component. The challenge I am facing is the inability to pass the last visible document snapshot required by the startAfter() query. Below is the fu ...

Having trouble with the line graph in Flot when a threshold is applied?

I'm currently working on a website where I am incorporating flot for data visualization. However, I'm facing an issue with setting a threshold on my line graph. Instead of coloring the data differently, it seems to be separating it at the thresho ...

How to Conceal the Search Bar in jQuery DataTables

I am having trouble hiding the default search bar in DataTables. Despite trying solutions from this thread, using bFilter:false completely disables filtering, rendering my search boxes in the footer non-functional. I have created a jsfiddle demonstration. ...

When a user clicks on a button, AJAX and jQuery work together to initiate a setInterval function that continually

Currently, I have two scripts in place. The first script is responsible for fetching a specific set of child nodes from an XML file through AJAX and using them to create a menu displayed as a list of buttons within #loadMe. What's remarkable about thi ...

What is the best way to save geolocation coordinates in a Javascript array?

I am attempting to utilize HTML5 geolocation to determine a user's location and then store the latitude and longitude coordinates in an array for future use with Google Maps and SQL statements. However, when I attempt to add these coordinates to the a ...

Asynchronously fetching a model in an Angular controller

I am faced with an issue in my controller where I have functions that refer to the model before it is fetched. This results in errors like "cannot read property of undefined" when the view tries to access certain attributes. To address this, I have tried ...