Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronously update progress bar base on the response from API

Description

enter image description here

Install device API

I have an API to install a device. When I hit it, API it will start install my device , and return a taskID

enter image description here

Monitor API

I will then use the taskID to pass on to another API call to track the progress of installing.

Monitor API will return an integer from 1 - 200, which is the percentage of my progress of my installing.


My goal

is to keep calling the monitor API, and asynchronously update my progress bar real time. When it reach 200, it is done, I will hide the progress bar and show success message.

enter image description here


I've tried

Logic

  1. Call the API
  2. Wait 1 s
  3. Call the API again if still not reach 200 yet
  4. Repeat
  5. Until I got 200 percent
  6. Then get out of the loop
  7. Finish

core-code

enter image description here

Code

var ajax = $.ajax({

    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value')},
    url: '/installDevice',
    type: 'POST',
    dataType: 'json',
    data: {'security-level':'medium'}

});

ajax.done(function ($installDeviceResponse) {

    console.log($installDeviceResponse);

    if($installDeviceResponse['result'][0]['status']['code'] == 0){

        var taskId = $installDeviceResponse['result'][0]['data']['task'];
        var $percent  = 0;
        do {

            $.ajax({url: '/monitor/'+taskId})
            .done(function ($percent) {
                setTimeout(function(){
                    console.log('P TaskIdResponse : ',$percent);
                    
                    // update prograssbar
                    // I don't have this yet.
                    // I'm trying to print it out for now

                }, 1000);
            });
        }
        while ($percent < 200);

    }else{
        var message = $installDeviceResponse['result'][0]['status']['message'];
        var code = $installDeviceResponse['result'][0]['status']['code'];
        console.error('Error code :  ' + code + ' ' + message );
    }

});

return;

I put the timer of 1s because I don’t want to DDOS the API server.


Result

The result I got is infinite loop.

I don't have a progress bar added yet since I want to get the code working in the console first. All I got now is the loading icon.

The loading icon seem to freeze.

enter image description here

The console seem to freeze, cannot even expand 1 of my response.

enter image description here

The computer is making a lot of fan noise because of high CPU usage. The Chrome response is laggy.

How can I debug this?

like image 404
code-8 Avatar asked Mar 04 '18 02:03

code-8


1 Answers

You are trying to do a polling but in a wrong way. I will show you the examples.

Method 1 using Jquery ajax

function poll(){
  $.ajax({ url: "server", success: function(data){
    //Update your dashboard gauge
    console.log('P TaskIdResponse : ',$percent); 


   }, dataType: "json", complete: poll, timeout: 2000 });
})();

It is very fast it will poll once the previous request is ended.

Method 2 using setTimeout

// The setTimeout Technique (Not Recommended - No Queues But New AJAX Request Each Time ∴ Slow)
(function poll(){
  setTimeout(function(){
  $.ajax({ url: "server", success: function(data){
    //Update your dashboard gauge
    salesGauge.setValue(data.value);
    //Setup the next poll recursively
    poll();
  }, dataType: "json"});
}, 30000);
})();

Another Method that I have used for Creating a Long Polling and checking the user status.

 (function() {
  var status = $('.status'),
    poll = function() {
      $.ajax({
        url: 'status.json',
        dataType: 'json',
        type: 'get',
        success: function(data) { // check if available
          status.text('Offline!');
          if ( data.live ) { // get and check data value
            status.text(data.info); // get and print data string
            clearInterval(pollInterval); // optional: stop poll function
          }
        },
        error: function() { // error logging
          console.log('Error!');
        }
      });
    },
    pollInterval = setInterval(function() { // run function every 2000 ms
      poll();
      }, 2000);
    poll(); // also run function on init
})();

Hope this helps

like image 65
Romantic Dev Avatar answered Sep 27 '22 17:09

Romantic Dev