如何在JS中强制重绘? [英] How to force repaint in JS?
问题描述
我试图达到的效果:
- 用户点击元素
- 屏幕显示计算进行中屏幕
- 系统执行耗时的数学计算
- 屏幕显示结果(完成
$ b< div id =dionclick =calc()> initial< / div>
< script>
函数calc()
{
var n,a = 0;
document.getElementById('di')。textContent =正在计算中;
for(n = 0; n <1000000000; n ++)//这是费时的计算
{
a = a + n; //为了清楚起见,我在这里删除了复杂的数学公式
}
document.getElementById('di')。textContent =done+ a;
}
< / script>
当我运行它并点击div时,需要一段时间,然后将文本更改为完成,所以用户根本没有看到计算进行中消息 - 这是我的问题。
强制重画屏幕以在计算开始,其他线程建议修改CSS,隐藏和立即取消隐藏元素或使用setTimeout,但没有任何工作。
这将是一个程序,绘制复杂的数学对象(分形),我将使用画布而不是div,但是我简化了上面的示例。由于未来的图形界面,使用alert()不是一个选项 - 完成计算后,正在进行的计算屏幕应该立即变为完成。
解决方案您需要等待一毫秒或者使用Worker来执行计算。
第一个例子可能是最简单的,而不是直接调用
calc
,创建一个新函数
函数调用者(){
//在主体中插入进行中的计算
setTimeout(calc,1);
}
然后调用
caller
。What I am trying to achieve:
- user clicks on an element
- the screen shows the "calculation in progress" screen
- the system performs time-consuming math calculations
- the screen shows the result ("done")
Here's the stripped code:
<div id ="di" onclick="calc()">initial</div> <script> function calc() { var n,a=0; document.getElementById('di').textContent="calculation in progress"; for(n=0;n<1000000000;n++) // Here's the time consuming calculation { a=a+n; // for clarity's sake, I removed a complicated math formula here } document.getElementById('di').textContent="done "+a; } </script>
When I run it and click on the div, it takes a while and then changes the text to "done", so the user does not see the "calculation in progress" message at all - this is my problem.
To force a screen repaint to display the message before the calculations start, other threads suggest modifying CSS, hiding and immediately unhiding the element or using setTimeout, but nothing worked.
This will be a program that draws complicated math objects (fractals) and I will use canvas instead of a div, but I simplified the example above. Because of the future graphic interface, using "alert()" is not an option - the "calculation in progress" screen should turn to "done" immediately upon completion of the calculations.
解决方案You need to either wait a millisecond or do the calculations with a Worker.
The first example is probably the easiest, instead of calling
calc
directly, create a new functionfunction caller() { // insert "calculation in progress" in the body setTimeout(calc, 1); }
Then call
caller
.这篇关于如何在JS中强制重绘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!