My question is very similar to the one described in this post:
Javascript progress bar not updating 'on the fly', but all-at-once once process finished?
I have a script that calls a few services, and processes some actions.
I’m trying to create a progressbar that indicates the current status of script execution to the end user. I calculate the process (#currentaction / #totalactions) to indicate the progress and update the DOM each time an action is processed with this new value.
However, the DOM is only updated when all actions are finished.
I have placed a setTimeout in my function, and for some reason the DOM is still not updating step by step, it’s only updating when the entire jscript is executed.
here’s an example of my JScript
var pos = RetrievePos();
_TOTALCOUNT = (pos.length);
for(var i = 0; i < pos.length; i++) {
var cpos = pos[i];
CreateObject(cpos, id);
}
function CreateObject(cpos, id)
{
setTimeout(function() {
//do work here, set SUCCESS OR ERROR BASED ON OUTCOME
...
//update gui here
var scale = parseFloat(_SUCCESS + _ERRORS) / parseFloat(_TOTALCOUNT);
var totWidth = $("#loaderbar").width();
$("#progress").width(parseInt(Math.floor(totWidth * scale)));
}, 500);
}
I’ve tried setting the setTimeout function around the entire CreateObject call, around the DOM calls only, but nothing seems to do the trick.
I’m probably missing something very obvious here, but I really don’t see it.
Any ideas?
Thanks,
The reason your code isn’t working properly is that the
CreateObjectfunction will be called several times over in quick succession, each time immediately cueing up something to do 500ms later.setTimeout()doesn’t pause execution, it merely queues a function to be called at some future point.So, essentially, nothing will happen for 500ms, and then all of your updates will happen at once (technically sequentially, of course).
Try this instead to queue up each function call 500ms apart.
and remove the
setTimeoutcall fromCreateObject.Note the use of an automatically invoked function to ensure that the variable
iwithin the setTimeout call is correctly bound to the current value ofiand not its final value.