Display a brief message for a limited duration of two seconds when a timeout occurs

I've encountered an issue with the code below, where a message is displayed if a promise doesn't return after five seconds:

$timeout(function () {
        if (!$scope.promiseComplete && $scope.submitted) {
          $scope.message = {
            content: [{
              title: '',
              msg: 'Service down - created'
            }],
            type: 'error'
          };
          return;
        }
      }, 5000)

However, I only want this message to display for two seconds. I tried nesting timeouts and it achieved the desired result. Is it considered bad practice to use nested timeouts?

$timeout(function () {
        if (!$scope.promiseComplete && $scope.submitted) {
          $scope.message = {
            content: [{
              title: '',
              msg: 'Service down - Railcar ASN created'
            }],
            type: 'error'
          };
          $timeout(function(){
            $scope.message = null;
          }, 2000)
          return;
        }

      }, 5000)

Update: Following the advice provided here, I made the following adjustment:

 $timeout(function () {
        if (!$scope.promiseComplete && $scope.submitted) {
          $scope.message = {
            content: [{
              title: '',
              msg: 'Service down - created'
            }],
            type: 'error'
          };
          return $timeout(function(){
            $scope.message = null;
          }, 2000)
        }
      }, 5000)

Answer №1

$timeout is promise-based and allows for chaining promises. While nesting $timeouts or other promises may be considered an antipattern, it can still be done.

This type of promise chain

  $timeout(function () {
    if (!$scope.promiseComplete && $scope.submitted) {
      ...
      return $timeout(function(){
        $scope.message = null;
      }, 2000)
    }
  }, 5000)

ensures that there are no more than 2 levels of nesting, and the promise returned by the initial $timeout can be used to extend or test the entire promise chain.

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

Issue with AngularJS controller method not functioning properly when assigned to a Div

I am facing an issue with a login form and its controller. The login function is not triggering upon submitting the form for some reason. Here is the code snippet for the form within the larger view file: <div class="login-wrap" ng-controller="LoginCt ...

Can you provide the function that updates subscription and account details using Recurly JS?

Recurly has unfortunately declined to provide assistance with this issue. I must understand the specific format of the objects, as Recurly will not process any extra data or incorrect query arguments (which vary for each function). Ruby: subscription = ...

The URL for this page is not within the app's designated domains and will not open Facebook Dialogs (FB UI)

I am currently working on integrating Facebook UI Dialogs into my website. My goal is to add custom actions when users share a post from my site. I have created my app, added the app URL and domain (which is the same as the URL), and included all necessa ...

Identifying when a user has inputted incorrect $routeparams

How can I restrict user input to only "id" as a query parameter in the URL? $scope.$on('$routeUpdate', function () { var id = $routeParams.id //check if user has entered any params other than "id". //if yes do someting }); I want ...

Animating shapes in Three.js

Is it possible to animate the underlying shape of a mesh created using Three.js by drawing a shape and extruding it? For example: drawShape: function(){ var shape = new THREE.Shape(); shape.moveTo(0, 0); shape.arc(0,0,30,0,(Math.PI*1.9),true) ...

Exploring JSON data and making precise adjustments in JavaScript

I am attempting to create my own database using JavaScript and JSON, but I have encountered some issues along the way. My main struggle is figuring out how to extract specific content from a JSON file. After doing some research, I came across this code sn ...

How can I cancel a JavaScript timer set from a different function?

Can anyone help me with stopping the timer initiated by setInterval() in JavaScript? I need to be able to stop this timer through another function. Is it possible to kill all timers on the page using jQuery or JS? Below is the function where I started the ...

Eliminating elements from an array by analyzing the substring values

My task involves managing a list of roles stored in an array $scope.role = [];. The challenge is to display the selected role in a chip form with only the first 3 characters shown. To achieve this, I utilized substr(0,3) in my $scope.multiRoles array where ...

I am wondering about the proper method for deleting multiple records simultaneously in Ember Data

My current challenge involves managing a list of record IDs, such as [1, 20, 20]. The process of individually querying and deleting each item is proving to be quite inefficient. store.findRecord('post', 1).then(function(post) { post.deleteRec ...

Is your custom login form in Web2py not submitting properly?

My attempt to customize the login form for web2py has hit a roadblock. Despite adding the necessary fields and submit button, nothing seems to be happening. Here's what the code in the form's view looks like: {{include 'web2py_ajax.html&apo ...

Error: JSON parsing failed due to an unexpected character, resulting in null data

Many people have asked similar questions on the same topic, but I have not been able to find a solution for my specific problem. Below is the code snippet that I am working with: $.post("show_search_results.php", {location_name: ""+location_name+"", key: ...

jQuery's Offset().left is experiencing some issues and not functioning correctly

Do you have a question about the jQuery offset() function? On my website, I utilize it to show an "email a friend" window when the email icon is clicked. However, the problem is that the window ends up stuck to the right side of the browser's window ...

Click events registered using JQuery's .on() method are not functioning

After clicking on the link, I want to add HTML content following the element that has the class jstore-js-detailLink. However, my current method doesn't appear to be functioning: <a href="" class="jstore-js-detailLink">hello</a> <div ...

Retrieving JSON Data from an API with JavaScript/jQuery

Having some trouble with JSON parsing using jQuery and JavaScript. I'm trying to fetch weather information from the open weather simplest API, but for some reason it's not working. When I hardcode the JSON data into a file or my script, everythin ...

Tips for Utilizing PHP Without the Need to Refresh the Page

Below are the contents of three files with their respective code: Controler.php <iframe id="frame1" style="display:none"></iframe> <iframe id="frame2" style="display:none"></iframe> <button onClick="document.getElementById(&apo ...

Implement a delay for updating the style of a button by using the setTimeout function

Is it possible to create a button that, when clicked, changes color to green and then reverts back to its original style after 3 seconds? I am able to change the button color using an onClick event in my script. However, I encounter scope errors when tryi ...

Setting up a cherrypy server for sending events: a step-by-step guide

I have been working on a basic web app using Angular and CherryPy for prototyping purposes. Currently, I am uploading two files and then invoking an external Python program within CherryPy to process them using subprocess (popen). I have successfully imple ...

When I checked the error kind in MongoDB, I encountered an undefined value

After entering a valid ID following /user/ like 'http://localhost:5000/api/profile/user/5ee9fbe0e82023146c8a5230', the expected result is returned. However, in cases where an invalid ID is provided, I need to identify the type of error. To test t ...

Error: Unable to establish connection with local host (::1) on port 50106

I am currently in the process of developing a Discord bot using Node.js and erela.js. However, I encountered an error when attempting to retrieve the server that handles erela: A node error occurred: connect ECONNREFUSED ::1:50106 2020-05-01T21:23:19.367 ...

Navigating within two containers using the anchorScroll feature in AngularJS

I am trying to create a page with two columns of fixed height. The content in each column is generated using ng-repeat directive. Is it possible to implement scrolling within each column to a specific id using AngularJS? Code <div> Scroll to a p ...