How do I make A and B run in parallel? - javascript

How do I make A and B run in parallel?
async function runAsync(funcName)
{
console.log(' Start=' + funcName.name);
funcName();
console.log(' End===' + funcName.name)
};
function A()
{
var nowDateTime = Date.now();
var i = 0;
while( Date.now() < nowDateTime + 1000)
i++;
console.log(' A i= ' + i) ;
}
function B()
{
var nowDateTime = Date.now();
var i = 0;
while( Date.now() < nowDateTime + 1000)
i++;
console.log(' B i= ' + i) ;
}
runAsync(A);
runAsync(B);
The console shows that A starts first and B starts after A:
Start=A
A i= 6515045
End===A
Start=B
B i= 6678877
End===B
Note:
I am trying to use async for Chrome/Firefox, and keep the JS code compatible with IE11.
This C# code generates the proxy function runAsync:
if (isEI())
Current.Response.Write(" function runAsync(funcName){ setImmediate(funcName); }; ");
else
Current.Response.Write(" async function runAsync(funcName){ funcName(); } ");
https://jsfiddle.net/NickU/n2huzfxj/28/
Update.
My goal was to parse information and prepare (indexing and adding triggers) for an immediate response after user input. While the user is viewing the information, the background function has 3-10 seconds to execute, and the background function should not block UI and mouse and keyboard responses. Here is the solution for all browsers, including IE11.
Created a new Plugin to simulate parallel execution of funcRun during idle times.
Example of an original code:
$("input[name$='xxx'],...").each( function(){runForThis(this)}, ticksToRun );
The updated code using the Plugin:
$(document).zParallel({
name: "Example",
selectorToRun: "input[name$='xxx'],...",
funcRun: runForThis
});
Plugin.
(function ($)
{
// Plugin zParallel
function zParallel(options)
{
var self = this;
self.defaults = {
selectorToRun: null,
funcRun: null,
afterEnd: null,
lengthToRun: 0,
iterScheduled: 0,
ticksToRun: 50,
showDebugInfo: true
};
self.opts = $.extend({}, self.defaults, options);
}
zParallel.prototype = {
init: function ()
{
var self = this;
var selector = $(self.opts.selectorToRun);
self.lengthToRun = selector.length;
if (self.lengthToRun > 0)
{
self.arrayOfThis = new Array;
selector.each(function ()
{
self.arrayOfThis.push(this);
});
self.arrayOfThis.reverse();
self.opts.iterScheduled = 0;
self.whenStarted = Date.now();
self.run();
return true;
}
else
{
this.out('zParallel: selector is empty');
return false;
}
},
run: function ()
{
var self = this;
var nextTicks = Date.now() + self.opts.ticksToRun;
var _debug = self.opts.showDebugInfo;
if (self.opts.iterScheduled === 0)
{
nextTicks -= (self.opts.ticksToRun + 1); // Goto to Scheduling run
}
var count = 0;
var comOut = "";
while ((self.lengthToRun = self.arrayOfThis.length) > 0)
{
var curTicks = Date.now();
if (_debug)
{
comOut = self.opts.name + " |" + (curTicks - self.whenStarted)/1000 + "s| ";
if (self.opts.iterScheduled === 0)
this.out("START " + comOut + " remaining #" + self.lengthToRun);
}
if (curTicks > nextTicks)
{
self.opts.iterScheduled++;
if ('requestIdleCallback' in window)
{
if (_debug)
this.out(comOut + "requestIdleCallback , remaining #" + self.lengthToRun + " executed: #" + count);
window.requestIdleCallback(function () { self.run() }, { timeout: 1000 });
} else
{
if (_debug)
this.out(comOut + "setTimeout, remaining #" + self.lengthToRun + " executed: #" + count);
setTimeout(function (self) { self.run()}, 10, self);
}
return true;
}
var nexThis = self.arrayOfThis.pop();
self.opts.funcRun(nexThis);
count++;
}
if (self.opts.afterEnd!== null)
self.opts.afterEnd();
if (_debug)
this.out("END " + comOut + " executed: #" + count);
return true;
},
out: function (str)
{
if (typeof console !== 'undefined')
console.log(str);
}
};
$.fn.zParallel = function (options)
{
var rev = new zParallel(options);
rev.init();
};
})(jQuery);
// Examples.
(function ($)
{
var tab1 = $('#tbl1');
for (i = 0; i < 1000; i++)
$("<tr>"+
"<td>#" + i + "</td>"+
"<td><input id='a_" + i + "' value='" + i + "' >"+
"</td><td><input id='b_" + i + "' value='" + i + "' ></td></tr>")
.appendTo(tab1);
$(document).zParallel({
name: "A",
selectorToRun: "input[id^='a_']",
funcRun: function (nextThis)
{
var $this = $(nextThis);
var nowDateTime = Date.now();
var i = 0;
while( Date.now() < nowDateTime + 2)
i++;
$this.val( i );
if (i > 100)
$this.css('color', 'green').css('font-weight', 'bold');
else
$this.css('color', 'blue');
}
});
$(document).zParallel({
name: "B",
selectorToRun: "input[id^='b_']",
funcRun: function (nextThis)
{
var $this = $(nextThis);
var nowDateTime = Date.now();
var i = 0;
while( Date.now() < nowDateTime + 2)
i++;
$this.val( i );
if (i > 100)
$this.css('background', '#BBFFBB');
else
$this.css('background', '#FFBBBB');
}
});
})(jQuery);
https://jsfiddle.net/NickU/1xt8L7co/59/

The two example functions simply execute synchronously one after the other on the same "thread" (JS effectively has only one thread available to such scripts).
The use of async is irrelevant here because no truly asynchronous operation is occurring in function A - it is simply a busy while loop - so it completes in full before execution can move to anything else.
If function A had called an actual asynchronous operation (such as a HTTP request - not simply a synchronous operation wrapped in an async function), then function B may have a chance to start up (in which case B would complete entirely before the execution returned to A, because B is also only contains a synchronous, busy while loop).
Parallel processing can be achieved with WebWorkers which allowing running on background threads (actual separate threads).

Related

Calling setInterval multiple times then Clearing interval , polling not stopped

As my loop is so fast, the intervals are overlapping and not able to stop one timerId. here is my code:
data = ['115536', '117202']; // BARCODES AVAILABLE ON A4 SHEET //
var scan_delay = 500; // USER AVG SCANNING SPEED PER BARCODE //
var timerId;
var scannedItemsList = []; // ITEMS WHICH ARE SCANNED BY SEEING A4 SHEET BY THE USER //
var tableDataList = []; // TO SHOW DATA WHICH WE GOT FROM API //
Jbin
try {
var data = ['115536', '117202']; // BARCODES AVAILABLE ON A4 SHEET //
var scan_delay = 500; // USER AVG SCANNING SPEED PER BARCODE //
var timerId;
var scannedItemsList = []; // ITEMS WHICH ARE SCANNED BY SEEING A4 SHEET BY THE USER //
var tableDataList = []; // TO SHOW DATA WHICH WE GOT FROM API //
execute(data);
function execute(data) {
var i = 0;
scanSimulatorWithADelay(data, i);
}
function scanSimulatorWithADelay(data, i) {
setTimeout(function () {
getJobDetailsByCallingAPI(data[i], i);
i++;
if (data.length > i) {
scanSimulatorWithADelay(data, i);
} else {
i = 0;
}
}, scan_delay);
}
function getJobDetailsByCallingAPI(jobNumber, index) {
scannedItemsList.push(jobNumber);
//poll_for_jobs_count_which_are_scanned_but_waiting_to_add_to_table
startPolling();
//Simulate API to get response after every 3 seconds//
var apiDelay = (index + 1) * 3000;
setTimeout(function () {
console.log('API CALLED AT ' + new Date().toLocaleTimeString());
CallTheAPI(jobNumber);
}, apiDelay);
}
function CallTheAPI(jobNumber) {
console.log("JOB NO " + jobNumber + " API response Recd");
tableDataList.push(jobNumber);
}
function startPolling() {
var pollStatus = '';
timerId = setInterval(() => {
debugger;
console.log('timerId when starting interval ' + timerId);
var jobsWhichAreScannedButNotLoaded = jobsWhichAreScannedButNotLoadedStill();
console.log("$$$$$$ jobsWhichAreScannedButNotLoaded = " + jobsWhichAreScannedButNotLoaded.length);
if (jobsWhichAreScannedButNotLoaded.length === 0) {
console.log("### Inteval Cleared ### " + timerId);
//CLEAR TIMER
clearInterval(timerId);
} else {
pollStatus = 'Polling inprogress and the pollID ' + timerId;
}
console.log('####' + pollStatus);
}, 2000);
}
function jobsWhichAreScannedButNotLoadedStill() {
let stillLoadingJobs = [];
scannedItemsList.forEach(scannedItemsListJobNumber => {
let foundJobInsideTable = false;
if (scannedItemsListJobNumber) {
foundJobInsideTable = tableDataList.indexOf(scannedItemsListJobNumber) > -1;
if (!foundJobInsideTable) {
stillLoadingJobs.push(scannedItemsListJobNumber);
}
}
}); // End of scannedItemsList forEach loop
if (stillLoadingJobs.length > 0) {
return stillLoadingJobs;
}
return [];
}
} catch (error) { throw error; }
Your timer_id variable is on the global scope and hence overwritten every time you call startPolling.
So when you'll call clearInterval(timer_id), timer_id will be the id of the last setInterval, and the first one will keep running endlessly.
Simply add a var in your startPolling function so that timer_id be scoped correctly, and that it doesn't get overwritten by next call.
try {var data = ['115536', '117202'];
var scan_delay = 500;
// remove this one
//var timerId;
var scannedItemsList = [];
var tableDataList = [];
execute(data);
function execute(data) {
var i = 0;
scanSimulatorWithADelay(data, i);
}
function scanSimulatorWithADelay(data, i) {
setTimeout(function () {
getJobDetailsByCallingAPI(data[i], i);
i++;
if (data.length > i) {
scanSimulatorWithADelay(data, i);
} else {
i = 0;
}
}, scan_delay);
}
function getJobDetailsByCallingAPI(jobNumber, index) {
scannedItemsList.push(jobNumber);
//poll_for_jobs_count_which_are_scanned_but_waiting_to_add_to_table
startPolling();
//Simulate API to get response after every 3 seconds//
var apiDelay = (index + 1) * 3000;
setTimeout(function () {
console.log('API CALLED AT ' + new Date().toLocaleTimeString());
CallTheAPI(jobNumber);
}, apiDelay) ;
}
function CallTheAPI(jobNumber) {
$.ajax({
url: "https://jsonplaceholder.typicode.com/todos/1",
type: "GET",
async: true,
success: function (response) {
console.log("JOB NO " + jobNumber + " API response Recd");
tableDataList.push(jobNumber);
}
});
}
function startPolling() {
var pollStatus = '';
/////////
///HERE
/////////
// Declare timerId in startPolling scope
/////////
var timerId = setInterval(() => {
debugger;
console.log('timerId when starting interval '+ timerId);
var jobsWhichAreScannedButNotLoaded = jobsWhichAreScannedButNotLoadedStill();
console.log("$$$$$$ jobsWhichAreScannedButNotLoaded = "+ jobsWhichAreScannedButNotLoaded.length);
if (jobsWhichAreScannedButNotLoaded.length === 0) {
console.log("### Inteval Cleared ### "+ timerId);
//CLEAR TIMER
clearInterval(timerId);
} else {
pollStatus = 'Polling inprogress and the pollID ' + timerId;
}
console.log('####' + pollStatus);
}, 2000);
}
function jobsWhichAreScannedButNotLoadedStill() {
let stillLoadingJobs = [];
scannedItemsList.forEach(scannedItemsListJobNumber => {
let foundJobInsideTable = false;
if (scannedItemsListJobNumber) {
foundJobInsideTable = tableDataList.indexOf(scannedItemsListJobNumber) > -1;
if (!foundJobInsideTable) {
stillLoadingJobs.push(scannedItemsListJobNumber);
}
}
}); // End of scannedItemsList forEach loop
if (stillLoadingJobs.length > 0) {
return stillLoadingJobs;
}
return [];
}
} catch (error) { throw error; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to loop a function in Javascript?

I am trying to create a countdown with JQuery. I have different times in an array. When the first time ist finished, the countdown should count to the next time in the array.
I try to do this with the JQuery countdown plugin:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
while (i < time.length) {
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
i++;
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
This does not work... But how can i do this?
You should never use a busy wait especially not in the browser.
Try something like this:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
var $counter = $("#countdown");
function countdown() {
var goal = date + " " + time[i];
$counter.countdown(goal, function(event) {
if (event.elapsed) {
i++;
if (i < time.length) {
countdown();
}
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
You can't use while or for loop in this case, because the operation you want to perform is not synchronous.
You could do for example something like this with the helper (anonynous) function:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
(function countdown(i) {
if (i === time.length) return;
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
countdown(i++);
} else {
$(this).text(event.strftime('%H:%M:%S'));
}
});
})(0)
You need to restart the countdown when the previous one finishes, at the minute you're starting them all at the same time.
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
function startCountdown(i) {
if(i >= i.length) {
return;
}
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
startCountdown(i++);
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
startCountdown(0);

Stop function from re- executing for one second with settimeout

I want to prevent my function from re-executing for one second after it's last executed. I've tried the method below, but it doesn't work.
function displayOut() {
// images
document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
// Diologue box
diologueBox.innerHTML = ""; // Clear Box
teleTyperDiologue(db.rooms[roomLoc].description +
" The room contains: " +
(function() {
let x = "";
for (let i = 0; i < db.items.length; i++) {
if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
x += db.items[i].name + ", "
}
}
x = x.slice(0, x.length -2);
if (x === "") {
x = " nothing of special interest";
}
return x;
})()
+ ".");
pause();
};
function pause() {
setTimeout(function() {
// Wait one second!
}, 1000);
}
You could use a pattern like this:
var executing = false;
function myFunc() {
if(!executing) {
executing = true;
//Code
console.log('Executed!');
//End code
setTimeout(function() {
executing = false;
}, 1000);
}
}
setInterval(myFunc, 100);
So in your case, this would look like this:
var executing = false;
function displayOut() {
if(!executing) {
executing = true;
// images
document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
// Diologue box
diologueBox.innerHTML = ""; // Clear Box
teleTyperDiologue(db.rooms[roomLoc].description +
" The room contains: " +
(function() {
let x = "";
for (let i = 0; i < db.items.length; i++) {
if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
x += db.items[i].name + ", "
}
}
x = x.slice(0, x.length -2);
if (x === "") {
x = " nothing of special interest";
}
return x;
})()
+ ".");
setTimeout(function() {
executing = false;
}, 1000);
}
};
Try to use throttle (http://underscorejs.org/#throttle) or debounce (http://underscorejs.org/#debounce) from underscore, one of those should fit your needs
This one will achieve that:
function run () {
console.log('Im running');
pause(1000);
};
function pause(s) {
console.log('Im paused');
setTimeout(() =>{
run();
}, s)
};
run();
The code above will run every 1 sec but if you want to make sure the function cant be runned again until you decide then you could use a flag instead like:
let canExecute = true;
function run () {
if (canExecute) {
console.log('Im running');
canExecute = false;
pause(1000);
}
};
function pause(s) {
console.log('Im paused');
setTimeout(() =>{
canExecute = true;
}, s)
};
run();
run();
run();
setTimeout(() =>{
run();
}, 2000)
This code will execute run function twice, first on time and then one more after 2 sec.

Trying to display and update map markers using Leaflet JS

I'm trying to display countdown timers until each of my markers disappear on my map. The markers disappear when their respective timers run out, but the timers themselves are not displaying below the markers themselves as they should. I checked the Developer Console and noticed there are a couple errors:
Uncaught TypeError: Cannot read property 'innerHTML' of null
Uncaught ReferenceError: component is not defined
This error count keeps increasing until it stops at a high number. I'm guessing this is when the particular timer runs out because after that number stops climbing the same error is logged again and the number starts from 1 and continues to climb.
L.HtmlIcon = L.Icon.extend({options: {},
initialize: function(options) {
L.Util.setOptions(this, options);
},
createIcon: function() {
//console.log("Adding pokemon");
var div = document.createElement('div');
div.innerHTML =
'<div class="displaypokemon" data-pokeid="' + this.options.pokemonid + '">' +
'<div class="pokeimg">' +
'<img src="data:image/png;base64,' + pokemonPNG[this.options.pokemonid] + '" />' +
'</div>' +
'<div class="remainingtext" data-expire="' + this.options.expire + '"></div>' +
'</div>';
return div;
},
createShadow: function() {
return null;
}
});
var map;
function deleteDespawnedPokemon() {
var j;
for (j in shownMarker) {
var active = shownMarker[j].active;
var expire = shownMarker[j].expire;
var now = Date.now();
if (active == true && expire <= now) {
map.removeLayer(shownMarker[j].marker);
shownMarker[j].active = false;
}
}
}
function createPokeIcon(pokemonid, timestamp) {
return new L.HtmlIcon({
pokemonid: pokemonid,
expire: timestamp,
});
}
function addPokemonToMap(spawn) {
var j;
var toAdd = true;
if (spawn.expiration_timestamp_ms <= 0){
spawn.expiration_timestamp_ms = Date.now() + 930000;
}
for (j in shownMarker) {
if (shownMarker[j].id == spawn.encounter_id) {
toAdd = false;
break
}
}
if (toAdd) {
var cp = new L.LatLng(spawn.latitude, spawn.longitude);
var pokeid = PokemonIdList[spawn.pokemon_id];
var pokeMarker = new L.marker(cp, {
icon: createPokeIcon(pokeid, spawn.expiration_timestamp_ms)
});
shownMarker.push({
marker: pokeMarker,
expire: spawn.expiration_timestamp_ms,
id: spawn.encounter_id,
active: true
});
map.addLayer(pokeMarker);
pokeMarker.setLatLng(cp);
}
}
//TODO:<--Timer Functions-->//
function calculateRemainingTime(element) {
var $element = $(element);
var ts = ($element.data("expire") / 1000 | 0) - (Date.now() / 1000 | 0);
var minutes = component(ts, 60) % 60,
seconds = component(ts, 1) % 60;
if (seconds < 10)
seconds = '0' + seconds;
$element.html(minutes + ":" + seconds);
}
function updateTime() {
deleteDespawnedPokemon();
$(".remainingtext, .remainingtext-tooltip").each(function() {
calculateRemainingTime(this);
});
}
setInterval(updateTime, 1000);
//<--End of timer functions-->//
Here is my JSFiddle for a full view of the situation.
Any idea what I'm doing wrong?
SolutionThanks to user T Kambi for pointing out the issue!
I forgot to include the component() function.
function component(x, v) {
return Math.floor(x / v);
}
After including this all works as intended.

$.each not updating css width

So I have a loop, which performs an ajax call on each iteration and I want to set the progress bar updated.. But it is not updating, it goes to 100% directly when ending...
I've tried to put the bar update call outside the success action (inside the loop directly) but it isn't working either..
$('button.page').on('click', function(e){
var $userList = textArray($('#page-userlist').val().replace('http://lop/', '').split(/\n/));
var $proxyList = textArray($('#page-proxylist').val().replace('http://', '').split(/\n/));
var $question = $('#page-question').val();
var data = {
question: $question,
users: $userList,
proxies: $proxyList
};
var i = 0, p = 0, max = data.proxies.length, totalusers = data.users.length, percent = 0;
$('#log').append("\n" + moment().calendar() + "\n");
var progressbar = $('#page-progress');
$.each(data.users, function(k, u){
if(typeof(p) !== 'undefined' && p !== null && p > 0)
{
if(i % 10 == 0 && i > 1) p++;
if(p == max) return false;
}
var proxy = data.proxies[p];
percent = Math.round((i / totalusers) * 100);
$.ajax({
type: "POST",
url: Routing.generate('viral_admin_bot_page'),
data: {question: $question, user: u, proxy: proxy},
success: function(result) {
$('#log').append("\nAtacado usuario " + u + " con proxy: " + proxy + "\n");
$(progressbar).width(percent + "%");
},
error: function(error) {
$('#log').append(error);
}
});
i++;
});
});
If i do console.log(percent); it is updating perfectly on each iteration, so I don't know where can be the problem.
Here is my code (without the ajax call because it isn't the problem) http://jsfiddle.net/dvo1dm03/20/
it will output to console the percentage, the objetive is to update the bar to the percentage completed in each loop, so it goes in "realtime" with loop.
Ok, here's how to do it asynchrounously.
var speed = 75;
var number_of_calls_returned = 0; // add number_of_calls_returned++ in your ajax success function
var number_of_total_calls;
var loaded = false;
function processUserData(){
if( number_of_calls_returned < number_of_total_calls){
setTimeout(function(){processUserData();}, 200);
}
else{
//received all data
// set progressbar to 100% width
loaded = true;
$("#page-progress").animate({width: "100%"},500);
$("#page-proxylist").val("Received data");
}
}
function updateProgress(percent, obj){
setTimeout(function(x){
if(!loaded)
$(obj).width(x + "%");
}, percent*speed, percent);
}
$('button.page').on('click', function (e) {
var $userList = textArray($('#page-userlist').val().replace('http://lop/', '').split(/\n/));
var $proxyList = textArray($('#page-proxylist').val().replace('http://', '').split(/\n/));
var $question = $('#page-question').val();
var data = {
question: $question,
users: $userList,
proxies: $proxyList
};
var i = 0,
p = 0,
max = data.proxies.length,
totalusers = data.users.length,
percent = 0;
//$('#log').append("\n" + moment().calendar() + "\n");
var progressbar = $('#page-progress');
number_of_total_calls = totalusers;
$.each(data.users, function (k, u) {
if (typeof (p) !== 'undefined' && p !== null && p > 0) {
if (i % 10 == 0 && i > 1) p++;
if (p == max) return false;
}
var proxy = data.proxies[p];
percent = (i / totalusers) * 100; //much smoother if not int
updateProgress(percent, progressbar);
i++;
// simulate ajax call
setTimeout(function(){number_of_calls_returned++;}, Math.random()*2000);
});
//callback function
setTimeout(function(){processUserData();}, 200);
});
var textArray = function (lines) {
var texts = []
for (var i = 0; i < lines.length; i++) {
// only push this line if it contains a non whitespace character.
if (/\S/.test(lines[i])) {
texts.push($.trim(lines[i]));
}
}
return texts;
}
Check it out here! jsFiddle (really cool!)
Your problem is cause by the fact that you have a closure for your success function and every success function shares the same percent variable. You can fix it like this:
success: function(percent, result) {
$('#log').append("\nAtacado usuario " + u + " con proxy: " + proxy + "\n");
$(progressbar).width(percent + "%");
}.bind(percent),
Where you'll need to shim bind in older browsers, or like this, which is a little uglier, but should work everywhere without a shim:
success: (function(percent) { return function(result) {
$('#log').append("\nAtacado usuario " + u + " con proxy: " + proxy + "\n");
$(progressbar).width(percent + "%");
}; }( percent ),
if what you want is to increase the update bar with each success of AJAX calls I'd suggest an easier solution (I've simplified the js code for clarity's sake):
$('button').click(function (e) {
var i = 0,
cont = 0,
totalusers = 100,
percent = 0;
var progressbar = $('#page-progress');
for (; i < totalusers; i++) {
$.ajax({
type: "POST",
url: '/echo/json/',
data: {
question: 'something',
user: 1,
proxy: 2
},
success: function (result) {
cont += 1;
percent = Math.round((cont / totalusers) * 100);
progressbar.width(percent + "%");
},
error: function (error) {
$('#log').append(error);
}
});
};
});
You can see it in action in this fiddle.
Hope this helps or at least give you some ideas.
Update the progress bar using setTimeout method.
it will wait for some time and then update the width of progressbar.
myVar = setTimeout("javascript function",milliseconds);
Thanks,
Ganesh Shirsat
I would like to make a recommendation of trying to make a self contained example that doesn't rely on the post so that it is easier for you or us to solve the problem
As well, you can console log elements so you could try logging the progressbar element, percent and the response of the ajax request
(This code is to replace the javascript sections of the fiddler)
var i = 0;
moveProgress();
function moveProgress(){
if(i < 10000)
{
setTimeout(function(){
$('#page-progress').width((i / 1000) * 100);
moveProgress();
},2);
i++;
}
}
The reason that it wasn't working was because the loop ran so fast that it was loaded by the time the script loaded it, the timeout allows you to delay the execution a bit(Though not necessarily recommended to use because of potential threading issues.

Categories