How can I force the browser to redraw while my script is doing some heavy processing?

8 html javascript css dom

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?

Bre*_*ton 14

浏览器是单线程的.在脚本运行时,浏览器无法执行任何其他操作.如果你想做一个像进度表这样的东西,你必须使用setTimeout(),或者setInterval()将你的任务分解成一个间隔运行的小块.这会在脚本运行之间留下空白,将控制权交还给浏览器,浏览器可以重新绘制.


小智 6

尝试定期中断脚本.你应该可以使用

setTimeout(nextFunction, 0); 
Run Code Online (Sandbox Code Playgroud)

在没有长时间延迟的情况下提供必要的中断,其中nextFunction是继续进行冗长处理的函数.