admin管理员组文章数量:1425761
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
- Call the API
- Wait 1 s
- Call the API again if still not reach 200 yet
- Repeat
- Until I got 200 percent
- Then get out of the loop
- 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
- Call the API
- Wait 1 s
- Call the API again if still not reach 200 yet
- Repeat
- Until I got 200 percent
- Then get out of the loop
- 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
1 Answer
Reset to default 2You 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
本文标签: javascriptAsynchronously update progress bar base on the response from APIStack Overflow
版权声明:本文标题:javascript - Asynchronously update progress bar base on the response from API - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745453659a2659001.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论