Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to report progress of a JavaScript function?

I have a JavaScript function which is quite long and performs a number of tasks, I would like to report progress to the user by updating the contents of a SPAN element with a message as I go. I tried adding document.getElementById('spnProgress').innerText = ... statements throughout the function code.

However, whilst the function is executing the UI will not update and so you only ever see the last message written to the SPAN which is not very helpful.

My current solution is to break the task up into a number of functions, at the end of each I set the SPAN message and then "trigger" the next one with a window.setTimeout call with a very short delay (say 10ms). This yields control and allows the browser to repaint the SPAN with the updated message before starting the next step.

However I find this very messy and difficult to follow the code, I'm thinking there must be a better way. Does anyone have any suggestions? Is there any way to force the SPAN to repaint without having to leave the context of the function?

Thanks

like image 679
LambyPie Avatar asked Apr 07 '10 12:04

LambyPie


1 Answers

The way you're doing it is the right way (at the moment, this may change as standards emerge and are adopted [see Andrew Aylett's answer], but not for a while yet). You have to yield like that to allow the browser to do its UI updates. I've found that the more I think like this, the cleaner things get, but my first few stabs at doing it were indeed quite "messy." Hopefully you find the same thing as you get used to it.

like image 173
T.J. Crowder Avatar answered Oct 07 '22 16:10

T.J. Crowder