8

I am using the innerHTML property to modify a DIV dynamically, to report on a process that takes a few seconds to finish. The problem is that on Firefox the page is not actually re-rendered to reflect that change until after the script has finished. This makes the app feel sluggish. Is there a way to make sure that changes to the HTML show up immediately, even if more scripts are running?

Shog9
  • 156,901
  • 35
  • 231
  • 235

2 Answers2

14

The browser is single threaded. While the script is running, the browser can't do anything else. If you want to do something like a progress meter, you have to use setTimeout(), or setInterval(), and break your task down into smaller chunks that get run on an interval. This leaves gaps in between the script runs, giving control back to the browser, where the browser can redraw.

Shog9
  • 156,901
  • 35
  • 231
  • 235
Breton
  • 15,401
  • 3
  • 59
  • 76
  • It seems not to be the case that browser is single threaded. It has one javascript thread but there is parallel thread which renders the page and manipulates the DOM – Sergey P. aka azure Dec 25 '13 at 12:51
  • That really depends on *which* browser you are talking about. Some may do that now, such as chrome with its multiprocess model- where each browser's content is a seperate process, and the chrome is also on its own process. but you can still easily hang any browser with `while(1)`. How much of the browser you hang depends on how the browser is built. – Breton Dec 27 '13 at 05:50
  • You can hang js thread by calling while(1) {}, but that doesn't mean that there's no other threads used for dom manipulation or content rendering. It means that JS thread possibly can block other threads execution. And threads may have no any relation to browser's proccess model (one process per page or one process for whole browser window) – Sergey P. aka azure Dec 29 '13 at 11:49
7

Try interrupting your script periodically. You should be able to use

setTimeout(nextFunction, 0); 

to provide the necessary interruption without a long delay, where nextFunction is the function that continues with your lengthy processing.

edsoverflow
  • 591
  • 3
  • 3