Contact a relaxation service periodically to pause its operation

To continuously check the status of a webservice, I need to make a REST call every x seconds (3000 ms) until the desired result is obtained or until it has been attempted 12 times. The call should also stop once the expected status is received:

function myFunction() {
    var i=0;
    var _onSuccess = function(response) {
        if (response.status=== 'READY' || i >= 12) {
            clearInterval(x);
            if(response.status !== 'READY') {
                $location.path('/errorView');
            }
        }
    }
    var x = setInterval(function () {
       $rest.getSomething(_onSuccess)
    }, 3000);
}

In addition to myFunction, there is another function that calls myFunction with a timeout. If the expected result is not received within 32 seconds, an error view is displayed.

function myFunction2() {
    myFunction();
    $timeout(function () {
        $location.path('/routeWhenStatusReady');
    }, 32000); 
}

Is there a way to optimize this process? I would like myFunction2 to finish its timeout after 16 seconds if the Ready status is confirmed instead of waiting for the full 32 seconds...

Thank you!

Answer №1

A suggestion would be to store the $timeout value in a variable:

let myTimeout = $timeout;

Then you can cancel it later on with:

$timeout.cancel(myTimeout);

Answer №2

Ensure to store the $timeout timer globally so that it is accessible by the myFunction. Remember to cancel the timer once you have achieved your desired outcome.

var timer = null;

function myFunction(){
    var i = 0;
    var _onSuccess = function(response){
        if (response.status === 'READY' || i >= 12) {
            clearInterval(x);
            if(timer){
              $timeout.cancel(timer);
            }
            if(response.status !== 'READY'){
                $location.path('/errorView');
            }
        }
    }
    var x = setInterval(function () {
        $rest.getSomething(_onSuccess)
    }, 3000);
}

function myFunction2(){
      myFunction();
      timer = $timeout(function () {
        $location.path('/routeWhenStatusReady');
      }, 32000); 
   }

Answer №3

First step:

Start by assigning $interval to a variable

 var timeHandler = $interval(() => {
                // your code
 }, 1000) };

Next step:

You can cancel the interval anytime by using the variable in the interval cancel function

$interval.cancel(timeHandler);

For more information, visit this site

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

Switching between languages dynamically with Angular JS using $translateProvider and JSON files

I currently have a collection consisting of 6 different JSON files. en.json es.json fr.json it.json ja.json zh.json An illustration of the data present in each file is as follows (in this instance, considering en.json): { "SomeText": "Test in Englis ...

Enclose each set of objects, such as text, within a separate div, except for div elements

Is there a way to wrap each immediate group of objects that are not contained in a div with a wrap class? Input: var $code = 'Lorem Ipsum <p>Foo Bar</p> <div class="myclass"></div> <p>Foo Bar</p> <div clas ...

Implementing an asynchronous task queue in AngularJS

I came across this JSFiddle example where three consecutive calls are made to a service function, simulating $http Request interceptor function which returns a promise. The current code does not wait for the previous call to finish before making the next o ...

Access nested objects in Javascript (Vue)

Struggling with a simple question as a beginner... I am dealing with an object of objects: monsters { place1: { monster1: { ... } monster2: { ... } } place2: { monster3: { ... } monster4: { ... } } } I ...

Transfer spoken words into a textbox using the keyboard-microphone feature on an iPad or mobile device

When we tap on a textbox on an iPad or mobile device in a web browser, the keyboard pops up on the screen. We have the option to choose the microphone and dictate the text directly into the input box using our voice instead of typing. Since speech convers ...

Tips for successfully executing child_process.exec within an ajax request

On a server that I have access to but not ownership of, there is a node js / express application running on port 3000. Various scripts are typically executed manually from the terminal or via cron job. My goal is to have a button on the client-side that tr ...

Using Dropzone.js to bypass the Browse dialog when uploading files in integration tests with php-webdriver

Currently, I am implementing dropzone.js in my project. I have a specific requirement where I need to manually add a file to the queue without triggering the file browser dialog box. The dropzone has been initialized on the element with the class .imageDro ...

Having trouble locating the module while importing MP3 files in a React project

UPDATE The issue stemmed from my limited understanding of the environment I was working in, but the responses provided below may be helpful for others facing similar challenges. EDIT: It appears that there is a problem with trying to import an mp3 file in ...

Style the code presented within a div tag

I am in the process of creating a JavaScript-powered user interface that can generate code based on user interactions. While I have successfully implemented the code generation functionality and saved the generated code as a string, I am facing difficultie ...

There is no index signature that accepts a parameter of type 'string' in the type '{ [key: string]: AbstractControl; }'

I'm currently tackling a challenge in my Angular project where I am creating a custom validator for a reactive form. However, I've encountered an error within the custom validators function that I am constructing. Below you will find the relevan ...

What is the best way to obtain the current cursor location in draft.js?

As part of my draftjs project, I'm working on implementing a feature that allows users to easily insert links. One approach I've taken is creating a popup that appears when the shortcut cmk + k is pressed. To enhance the user experience, I am cu ...

Is it possible to display the content below the row of the clicked element when it is selected?

I am currently working on building a team page similar to the layout at My goal is to create a row of elements that float or display inline, with hidden content revealed beneath each selected element, pushing subsequent rows further down. Unfortunately, m ...

What would be the counterpart of setLocale in Yup for the zod library?

How can I set default custom error messages for Zod validation? If I want to use i18n for error messages in Yup, I would do the following: import { t } from "i18next"; import * as yup from "yup"; import "./i18next"; yup.setL ...

The issue with Angular.js webpage routing seems to persist in my single-page application (SPA) despite my utilization of ng-view

I'm having trouble inserting a view into my index.html using $routeProvider and ng-view from the AngularJS libraries. Can anyone assist me in figuring out why it's not being inserted? Below is the code for my index.html, views, and app.js files: ...

Having difficulty using replaceWith to replace text in jQuery

My favorite script successfully adds data to SQL and replaces HTML tags. I have included a text like Add Favorite and used replaceWith to display Remove Favorite. However, the output is not as expected, as shown in the image below. https://i.sstatic.net/x ...

AngularJS ng-show feature causing a delay in displaying a div element

My experience with Angular is still in its early stages. One issue I encountered involves a file input element: <input type="file" id="sampleFile" onchange="angular.element(this).scope().vm.displaySelectedXml()" /> That is followed by a div: <d ...

The function designed to create in-line TailwindCSS classNames may work inconsistently in React and NextJS environments

Currently, I am utilizing TailwindCSS to style a web application. One frustrating aspect is that when attempting to add before: and after: pseudo-elements, it must be done individually. For instance, take the navigation drop-down button styling: <span ...

Issue with Vue2: encountering an error with the view-router component when attempting to utilize the <router-view> tag

Currently delving into Vue2 for the first time and facing hurdles with routes. Ever since I inserted <router-view></router-view> in index.html, an exception has been popping up: [Vue warn]: Failed to mount component: template or render functi ...

using jQuery to eliminate an HTML element based on its attribute

How can I remove an element with the attribute cursor = "pointer"? I want to achieve this using JavaScript in HTML. Specifically, I am looking to remove the following item: <g cursor="pointer"></g>. It's unclear to me why this element has ...

Tips for aligning a select and select box when the position of the select has been modified

Recently, I encountered an interesting issue with the default html select element. When you click on the select, its position changes, but the box below it fails to adjust its position accordingly. https://i.stack.imgur.com/SwL3Q.gif Below is a basic cod ...