javascript循环冻结浏览器,循环前看不到更改 [英] javascript loop freezes browser and can't see change before loop
本文介绍了javascript循环冻结浏览器,循环前看不到更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的javascript循环,如下所示:
I have a simple javascript loop as you seen below:
function runCode() {
$("#sample-span").removeAttr("style");
for (var i = 0; i < 100000; i++) {
console.log(new Date());
}
$("#sample-span").toggleClass("colorized");
}
页面中跨度的切换类如下:
That toggle class of span in the page as below:
<span id="sample-span" style="color: orange;">Sample Text</span>
<input type="button" value="click to run" onclick="runCode()" />
<style>
span {
color: blue;
}
.colorized {
color: red;
}
</style>
问题在于,当循环运行时,页面冻结,看不到跨度颜色的变化.
The problem is that when the loop is running the page freezes and can't see that span color changes.
我该如何解决这个问题?
How can I solve this problem?
更新
亲爱的,console.log(new Date());
只是一个示例,您假定这里运行的是繁重的javascript程序.
Dear all, console.log(new Date());
is just a sample, you assume that here is running heavy javascript procces.
推荐答案
在运行繁重的过程之前,您必须在更改颜色后添加一小段延迟:
You have to add a small delay after changing the color before running the heavy process:
function runCode() {
$("#sample-span").toggleClass("colorized");
setTimeout(runTask,10)
}
function runTask(){
for (var i = 0; i < 100000; i++) {
console.log(new Date());
}
$("#sample-span").toggleClass("colorized");
}
这篇关于javascript循环冻结浏览器,循环前看不到更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文