5

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,

Community
  • 1
  • 1
Nathan
  • 1,865
  • 4
  • 19
  • 25
  • 1. Where are `_SUCCESS`/`_ERRORS` defined? You should be at least initializing. 2. Is your `setTimeout` processing the "workload" in chunks (so you'll have multiple UI update calls?) – Brad Christie Oct 03 '11 at 13:14
  • 1
    If your DOM-changing code is in the setTimeout block, then you can reasonably expect the DOM to change 500 milliseconds in the future rather than now. – awm Oct 03 '11 at 13:15
  • _SUCCESS and _ERRORS are globally defined variables, I haven't included all code here, this was just a snippet. The code is executing perfectly fined, I've debugged it over and over. The only problem is that DOM is only updated when all code is executed, irregardless of the setTimeouts I use. The entire process takes about 20 seconds to complete, and the progressbar stays at 0, until the 20 secs have passed, and then moves to 100 %... – Nathan Oct 03 '11 at 13:20

3 Answers3

4

The reason your code isn't working properly is that the CreateObject function 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.

for (var i = 0; i < pos.length; i++) {
    setTimeout((function(i) {
        return function() {
            var cpos = pos[i];
            CreateObject(cpos, id);
        }
    })(i), i * 500);
}

and remove the setTimeout call from CreateObject.

Note the use of an automatically invoked function to ensure that the variable i within the setTimeout call is correctly bound to the current value of i and not its final value.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
0

I presume you are doing more than just the setTimeout within CreateObject ? If you are not, best just to call the setTimeout from the loop.

I suspect you are using JQuery. If so, try using animate

$('#progress').animate({width: parseInt(Math.floor(totWidth * scale)) }, 'slow');

Since that will invoke it's own updating code, it might solve the issue. Without your full code, I couldn't say exactly what the problem here is. I'm also a PrototypeAPI head and not a JQuery head.

gazhay
  • 131
  • 1
  • 11
  • I see the point has been covered well above. Just as an aside, it would probably make more sense to use a recurrent updater using setInterval or the JQuery and prototype alternatives. – gazhay Oct 17 '11 at 19:34
0

@gazhay: you probably have a point that using the .animate function of jQuery this problem could have been bypassed.

However, I found a solution for this problem. I modified the JScript to no longer use a for loop, but use recursive functions instead. Appearantly the DOM does not get updated untill the FOR loop is completely terminated... Can anyone confirm this?

I've tested this out with the following script:

This doesn't work:

for(var i = 0; i < 1000; i ++)
{
    setTimeout(function() {document.getElementById('test').innerHTML =  "" + i;}, 20);
}

While this does work:

function dostuff(i)
{
    document.getElementById("test").innerHTML = i;
    if(i<1000)
        setTimeout(function(){ dostuff(++i);}, 20);
}

var i = 0;
dostuff(i);
Nathan
  • 1,865
  • 4
  • 19
  • 25
  • 1
    no, the DOM will update quite happily in a `for` loop. See my answer for more detail, but essentially you were triggering _every_ pass of the loop to trigger in roughly 500ms from the start of the loop, whereas your recursive version doesn't queue the next pass until the previous one has finished. – Alnitak Oct 03 '11 at 14:50
  • You're right, Ive tried your solution as well, and it works as well! – Nathan Oct 04 '11 at 07:32