Display a loading spinner during an HTTP request in Appcelerator

As of now, I am facing a challenge in displaying a spinner while an HTTP request is being executed. Every time I try to implement a spinner, it stops animating as soon as the call starts.

var spinnerArray = [];
for (var i = 0; i < 20; i++) {
    spinnerArray.push('/images/preloaderGif/preloader'+ ("0" + i).slice(-2) + '.gif');
}
$.spinner.images = spinnerArray; 
$.spinner.duration = "200"; 
$.spinner.repeatCount = "0";

spin();

function spin(){
    $.spinner.start();
    callHTTP() //Prewritten function
    Ti.App.addEventListener('callEnd', function(e){
        $.spinner.stop();
    });
}

This issue causes the spinner to never actually show up on the screen. Removing the HTTP call or placing it within a timeout leads to the spinner spinning indefinitely or until the timeout finishes.

I am wondering if there is a way to keep the spinner animation running smoothly throughout the duration of the call?

Answer №1

There is actually a much simpler and efficient way to display an indicator. Follow these easy steps:

  1. First, download the widget called Loading Indicator Widget and add it to your project in the app->widgets folder. If the folder doesn't exist, create it.

  2. Next, insert this line "nl.fokkezb.loading" : "*" into your app->config.json file under the dependencies section (see screenshot below). https://i.sstatic.net/Mqkmo.png

  3. In your alloy.js file, include the line

    Alloy.Globals.loading = Alloy.createWidget("nl.fokkezb.loading");

Now you can easily show or hide the indicator when making HTTP requests using the following code snippet:

function callHTTP() {
    if (!Ti.Network.online) {
       return;
    }

    Alloy.Globals.loading.show();

    var xhr = Ti.Network.createHTTPClient({
        onerror : function(e) {
            Alloy.Globals.loading.hide();
        },

        onload : function(e) {
            Alloy.Globals.loading.hide();
           // additional code here
        },
    });

    xhr.open("GET", url);
    xhr.send();
}

callHTTP();

By using this widget, you eliminate the need for long and error-prone code in different projects. With just 2 lines of code, you can effortlessly show or hide the loading indicator.

Remember that XHR error/success callbacks are the only places where you should write code to hide the indicators, as the completion time of HTTP requests is unpredictable.

Answer №2

To display a loading spinner, you can utilize an ActivityIndicator component. Here is the documentation for more information:

$.activityIndicator.show();
var xhr = Ti.Network.createHTTPClient({
    onerror : function(e) {
        // error handling code
        $.activityIndicator.hide();
    },
    onload : function(e) {
        // success code
        $.activityIndicator.hide();
    },
});

xhr.open("GET", url);
xhr.send();

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

Having trouble with the Cordova button not functioning on Android 9? A beginner seeks assistance

I attempted to create a button with the id of "clickme" that links to index.html and js/buttonexample.js. Although I could see the button on both the browser and android emulator, it wasn't functioning as expected when clicked. js/buttonexample.js d ...

"Displaying slider position relative to total count before clicking on it for

Utilizing the Foundation Zurb 6/Orbit Slider. Is there a way to show the current slide count and total before the slidechange.zf.orbit event triggers? Should I integrate an event prior to this, on window load, or use another method? The first slide initi ...

The pairing of Transpiller and Internet Explorer 8 is like a dynamic

In starting my new project, I am considering using BabelJS. However, there is a significant requirement that must be met: it needs to be compatible with IE8. ISSUE: Babel compiles ES6 to ES5, but the support for ES5 on IE8 is lacking. Are there any alter ...

developing a dynamic map with javascript

In the image provided, my concept is for it to initially be without a green tint. However, when the user hovers over specific areas, they would turn green and become clickable links. There are multiple areas in the image, with this being just one example. ...

The history.replaceState() function is failing to execute within the script of an <iframe>

I am currently in the process of developing an addon. This addon will be displayed within an <iframe>. <div> <iframe src="my/add-on/path"> <!-- contents expanded here --> </iframe> </div> Within the a ...

Choose2 generateUniqueEntry identification from submission

I am currently using select2 for a tagging input, but I am facing some challenges when it comes to handling the creation of new tags and retrieving the new tag IDs back into the select2. This issue is closely tied to another question on this topic which c ...

You are only able to click the button once per day

I am working on a button that contains numeric values and updates a total number displayed on the page when clicked. I would like this button to only be clickable once per day, so that users cannot click it multiple times within a 24 hour period. Below i ...

Discovering the initial element in an array that meets a condition by employing an asynchronous function

I'm facing a rather peculiar issue. I need to locate the first element in an array that meets a certain condition, but the find function must be labelled as async because a promise is required for the search. Just to clarify, the code provided below ...

What is the best way to use JavaScript or jQuery to place divs in the desired position?

Here is the code snippet I am working with and I need assistance in positioning the div elements accordingly: <div id="outer" style="width:300px"> <canvas></canvas> <div id="inner"> <div class="a"> val1 </div> <div c ...

Activate the textbox without utilizing `.focus()` method

I am encountering an issue with a small iframe on my page. The content within the iframe is larger than the window itself, requiring users to scroll around to view it in its entirety. Within this iframe, there is a button that, when clicked, triggers an an ...

What causes JavaScript to not execute sequentially?

Here is some HTML/JavaScript code, but when the function calc() is called, it outputs an <ol> tag first, rather than running the script in order. I have removed the setTimeout() function to make it run synchronously. If anyone can provide an explana ...

Troubleshooting issues with the sidebar navigation in Laravel project using Vue and AdminLTE

I successfully installed AminLte v3 via npm in my Laravel + vue project and everything is functioning properly. However, I am facing an issue when I attempt to click on the main menu item in the Side navbar that is labeled as <li class="nav-item has-tr ...

How can I incorporate a CDN link into the newly updated Next.js App Router?

Exploring next.js has been quite an adventure for me, and I'm impressed with its capabilities. However, being a beginner, I have encountered some challenges. One issue I am currently facing is the difficulty in using Google icons without a CDN link in ...

Having issues with transferring user input on change to a parent component in React JavaScript

I encountered an issue while passing a method from a parent component to a child component. The parent component, FilterableProductTable, contains a state called filterText. It renders a child component named SearchBar and passes down a function called han ...

Designing a menu inspired by the layout of Google Plus

I am attempting to create a responsive menu that behaves similarly to the one on Google Plus. In this menu, main options are either added to or removed from the "more" dropdown as the window is resized. Here is the current appearance of my menu: Below is ...

Maintaining an object's position steady in relation to the camera in Three.js

I am trying to figure out how to maintain an object's position relative to the camera. Specifically, I want one object to be viewable from all angles using a trackball camera, while another object should always stay in the same position relative to th ...

Upgrade your AngularJS Directive to an Angular 2.x+ Directive by using an HTML decorator

Is it no longer possible to utilize Angular directives as what I like to refer to as "HTML decorators"? I found this method extremely useful in Angular 1.x when transitioning legacy applications to Single Page Apps by creating a set of directives to enhan ...

The expiration period set in expireAfterSeconds doesn't seem to be functioning as expected in the time-to-live (ttl) configuration. Rows are

Can you please take a look at my code and provide some feedback? The issue I am facing is that the record is getting deleted without specifying the number of seconds. I have tried changing from createIndex to ensureIndex but it's still not working as ...

Tips for setting a pre-selected default value in Angular's Chosen feature

I am implementing an angular chosen function on my select tag. Below is the code for my select tag: <select name="rname" id="rname" ng-model="rname" ng-init="rname='CustomReport'" ng-options="key as value for (key , value) in reportsValu ...

Customized wrapper for JQuery's ajax method. Callback is triggered without passing any parameters

As a newcomer to JavaScript, my questions may seem basic. I find myself frequently using GET and POST requests in my code, so I decided to create a wrapper function to streamline calling jQuery's ajax function. /** * Makes Get request * @param url ...