javascript - Asynchronously update progress bar base on the response from API - Stack Overflow

DescriptionInstall device APII have an API to install a device. When I hit it, API it will start insta

Description

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

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.


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

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.

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

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

How can I debug this?

Description

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

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.


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

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.

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

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

How can I debug this?

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Mar 4, 2018 at 2:23 code-8code-8 59k120 gold badges391 silver badges670 bronze badges 5
  • Crashed my browser testing lol, $percent wont update, so your do while will spawn a constant stream of ajax calls which will cause the dos.. – Lawrence Cherone Commented Mar 4, 2018 at 2:46
  • @LawrenceCherone - sorry. I'm working on it. Please be careful while testing this code. :) – code-8 Commented Mar 4, 2018 at 2:51
  • Use websockets, not ajax. Much better for you! Echo is installed out of the box, and you can spawn events from your code to update the position of the progress. You can setup the laravel echo server really easily, too – Ohgodwhy Commented Mar 4, 2018 at 3:09
  • Ideally you should never call api in loop Can you bind event . May be something like this -dave-bond./blog/2010/01/JQuery-ajax-progress-HMTL5 – Mrugank Dhimmar Commented Mar 4, 2018 at 3:12
  • 1 The $.ajax call is asynchronous, which means non-blocking, which means the code sends as many AJAX calls as it can, exhausting resources possible even before the first response is received. This looks like an infinite loop, but given infinite resource, the loop whould end at some stage. – RandomSeed Commented Mar 4, 2018 at 10:13
Add a ment  | 

1 Answer 1

Reset to default 2

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", plete: poll, timeout: 2000 });
})();

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

Method 2 using setTimeout

// The setTimeout Technique (Not Remended - 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745453660a4628385.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信