Executing a progress bar that increases by % increments every few seconds while simultaneously performing an ajax call

Here is a snippet from my object:

const qwData = {

    // Initialize functions
    init: function() {
        this.cacheDom();
        this.bindEvents();
    },
    // Cache vars 
    cacheDom: function() {
        this.dataDisplayed  = false;
        this.countUsers     = <?php echo $_SESSION['all_users_count_real']; ?>;
        this.$form          = $('#frm_reportit');
        this.start_date     = this.$form[0][9].value;
        this.end_date       = this.$form[0][10].value;
        this.dateCount      = this.countDays(this.start_date, this.end_date);
        this.show           = document.querySelector('#btn-show');
        this.downloadBtn    = document.querySelector('#download_summary_button');
        this.$dataContainer = $('#qw-data-container');
        this.$qwTable       = $('#qwtable');
        this.$qwTbody       = this.$qwTable.find('tbody');
        this.qwChart        = echarts.init(document.getElementById('main-chart'));
        this.progressBar    = document.querySelector('.progress-bar');
        Object.defineProperty(this, "progress", {
            get: () => {
               return this.progressPrecent || 0;
            },
            set: (value) => {

                if(value != this.progressPrecent){
                  this.setProgressBarValue(value);
                  this.qwChartProgress = this.returnNumWithPrecent(value);
                }
            }
        });
        this.qwChartProgress= this.progress;
    },
    // Bind click events (or any events..)
    bindEvents: function() {

        var that = this;

        // On click "Show" BTN
        this.show.onclick = this.sendData.bind(this);

        // On Change inputs
        this.$form.change(function(){
            that.updateDatesInputs(this);
        });

    },

sendData: function(e) {
    e.preventDefault();
    let that = this;

    $.ajax({
        type: 'POST',
        url: "/test/ajax.php?module=test_module",
        dataType: 'json',
        data: {
                start_ts: that.start_date,
                stop_ts: that.end_date, 
                submitted: true
        },
        beforeSend: function() {

            // Show Chart Loading 
            that.qwChart.showLoading({ 
                color: '#00b0f0', 
                // text: that.returnNumWithPrecent(that.progress)
                text: that.qwChartProgress
            });

            // If data div isn't displayed
            if (!that.dataDisplayed) {
                // Show divs loading
                that.showMainDiv();
            } else {
                that.$qwTbody.slideUp('fast');
                that.$qwTbody.html('');
            }
        },
        complete: function(){


            let timer = setInterval(that.incrementProgress, 500);

        },
        success: function(result){

            // Set progressbar to 100%
            that.setProgressBarTo100();

            // Show Download Button
            that.downloadBtn.style.display = 'inline-block';

            // Insert Chart Data
            that.insertChartData(result);

            // Insert Table Data
            that.insertTableData(result);
        }
    });

    that.dataDisplayed = true;
},
// In order to achieve the result of incrementing `this.progress` by 10% every 0.5 seconds, we need to add it within the setInterval function in the `complete:` section of the AJAX call. By doing this, the value will increase by 10% at intervals of 0.5 seconds.
incrementProgress: function(){
    this.progress += 10;
},
..... 
.............
....................

I am attempting to continuously update this.progress by adding 10% to its value every 0.5 seconds. Despite trying different approaches such as adding it into the beforeSend: and complete:, I have only achieved a static 0% progress bar without any time delays. Can someone guide me on the correct way to implement this feature?

Answer №1

defining a property called "progress" with get and set methods in this context to manage progress tracking for an object

The issue stemmed from not properly setting the value of this.progressPrecent when retrieving it, causing it to always be 0.

Answer №2

The issue at hand remains unchanged. Let me summarize it for you:

Here is my test definition:

var test = {
    progress: 0,
    increment:function(){
        this.progress = this.progress+10;
    }
}

test is { progress: 0, increment: function }

test.progress();

test is { progress: 10, increment: function }

setTimeout(test.increment, 20)

test is { progress: 10, increment: function } since method is passed by reference!!!

setTimeout( function(){test.increment() }, 20)

test is { progress: 20, increment: function } since the context is preserved!!!

Therefore, even if your timer is functioning correctly, it will still increase progress in a different context than intended.

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

'this' in Arrow functions does not have a reference to the calling context

Something seems off about the context in this code. I've left comments to describe my issue below: const cat = { //arrow function meow: () => { console.log(this); }, makeMeow(){ // Why does 'this' refer ...

Manipulating the display style of an element without using jQuery

Could anyone assist me with this issue? I am currently facing a challenge in making the following script functional. It is intended to hide the button after it has been clicked. The script is being called through Ajax and PHP, so I am unable to utilize jQ ...

Ensure that all links are opened in a new tab

When including _blank in the a href URL, my website contains various elements like iframes and ads from Adsense, Taboola,, etc. Currently, when a user clicks on an iframe or ad, it opens in the same window. Is there a way to ensure that all URLs (includin ...

Smooth animation is not being achieved with the Jquery dlmenu

I have implemented a multi-level navigation menu using a demo of the jquery dlmenu plugin v1.0.2. Although most of the functions are working smoothly, the CSS3 menu navigation lacks the fluidity of the jQuery left/right sliding effect. Is there a way to ...

Is it possible to showcase D3 charts on an .epub file?

For my research project, I am exploring the possibilities of .epub files and experimenting with embedding JavaScript code to display data visualizations. I am currently using calibre to convert an HTML file containing D3 scatterplots into an .epub. The s ...

Retrieving information from $resource.get() in AngularJS

Working with JSON and XML in AngularJS { itemNumber: "T00000245", lotNumber: "00004" } <jdeSerials> <itemNumber>T00000245</itemNumber> <lotNumber>00004</lotNumber> </jdeSerials> Dealing with Asynchronous Ca ...

Create a nickname for a property in JavaScript

It seems like a straightforward question, Is there an easy method to create an alternate name for a property (I believe this one is specific to String – but I'm not entirely sure), for example a = length // this line is pseudo code 'hello wo ...

Usage of Firebase data

Looking for assistance on how to retrieve data from Firebase Cloud Store. My code includes the Firebase configuration and app.js but I'm facing an issue where the page appears blank on localhost:3000 without any errors. Below is the firebase.js confi ...

Using ajax to pass date parameters to @url.action

I am encountering a problem in my ASP.NET MVC 4 application where I am using JAX code sourced from a StackOverflow post to pass Date parameters to a controller. Unfortunately, I am receiving an http 404 error that states: "The resource you are looking for ...

Learn the method of converting a new Date object into dd mm yy format, specifically 09-07-2020, with a solution given by me for achieving this

For those seeking a solution to retrieve the jQuery date 30 days prior in the format dd-mm-yy: var today = new Date() var priorDate = new Date().setDate(today.getDate() +30) which will provide the date before 30 days in the format 1142 ...

Effects of incorporating unnecessary packages on Vue.js performance

In my Vue.js component, I have imported the module useI18n from "vue-i18n" but have not utilized it anywhere within the component. Concerned about how this could affect performance, particularly in terms of bundle size and load times. Will importing a mod ...

You will be automatically redirected after the page refreshes a few times

I'm currently working on a project that includes a countdown timer. The timer starts at 5 seconds and when it reaches 0, the page automatically refreshes. My question is how can I make the program redirect to another page after the page has been refre ...

Developing user registration and authentication using Backbone.js in conjunction with Django Rest Framework

In the process of developing my app, I am utilizing backbone.js for the frontend and django-rest-framework for the backend. My goal is to enable user registration, login, logout functionality, and be able to verify whether a user is logged in using backbon ...

Show pagination control only when there are multiple pages in AngularJS using ui-bootstrap

Currently, I am working with ui-bootstrap pagination and facing an issue where the pagination controls are still visible even when all the results are displayed on a single page. A quick glance at the image below confirms this problem. It seems like a basi ...

"Although both jQuery and PHP are capable of setting the element attribute, it is only PHP that functions successfully

I have been trying to set an element attribute to adjust the range of a slider. Initially, I used ajax to fetch data from a php file and assign it to the attribute. The slider looked good with the value but unfortunately, it wasn't functioning as expe ...

Can a function be activated in JavaScript when location permission is declined?

Background: Following up on a previous question regarding the use of getCurrentPosition and async functions. I am currently working on The Odin Project and attempting to create a basic weather application. My goal is to include a feature that automatically ...

Encountering a cross-domain origin issue while using a Firefox add-on on localhost?

Trying to send an ajax request from a Firefox add-on to a local server seems to be causing some issues: $.ajax({type: "GET",url: "http://localhost:9000/getFoo?param=foo", success: function (data) { console.log("response: " + data); }, error: function(x ...

Removing the gap between the clicked point and the draw point in Html5 canvas

To better understand my issue, please refer to the image linked below: In the image, you can see that when I scroll down and click on the canvas to point a position, it creates space between the clicked point and where the line is drawn. Below is the cod ...

Guide to utilizing exact matching functionality in ExpressJs router

In my ExpressJs application, I have defined two routes like so: router.get("/task/", Controller.retrieveAll); router.get("/task/seed/", Controller.seed); When I make a request to /task/seed/, the Controller.retrieveAll function is call ...

The issue with the dispatch function not working in the Component props of React Redux

I'm struggling with my colorcontrol issue. I've been attempting to use this.props.dispatch(triggerFBEvent(fbID, method, params)) without success. Interestingly, it seems to work fine if I just use triggerFBEvent(fbID, method, params). However, I ...