我有一个带有一些javascript的简单html文件,该文件需要一些时间才能运行,并且我想在用户等待时显示一个动画加载程序gif。
问题是动画不起作用。
我尝试了一些解决方案。其中一些来自堆栈溢出,但实际上没有任何作用。
我仅限于使用IE8。
有人知道一个可行的解决方案吗?
我的代码:
<html>
<head>
<script type="text/javascript">
function RunAndShow() {
document.getElementById("circularG").style.display = "block";
window.setTimeout(function () {
var j = 0;
for (var i = 0; i < 2000000000; i++) {
j = i;
}
alert("done");
}, 1500);
}
</script>
</head>
<body>
<div id="circularG" style="width:200px;height:200px;display:none; background-image:url(ajax-loader.gif)">
</div>
<table>
<tr>
<td>
<a href="#" onclick="RunAndShow()">Run & Show</a>
</td>
</tr>
</table>
</body>
</html>
最佳答案
当您在RunAndShow
中长时间运行for循环时,JS进程变得很忙。因此,它阻止了浏览器中的UI线程。这是预期的行为。
您可以使用网络工作者来运行长时间运行的计算。但是由于您限于IE8,因此无法使用。
一种选择是使用setInterval / setTimeout并每次都部分执行繁重的计算,以使UI线程不会阻塞。
function RunAndShow() {
document.getElementById("circularG").style.display = "block";
window.setTimeout(function () {
var computed = 0, process = 500, total = 10000000000, j;
var interval = setInterval(function() {
while(computed < process && process < total ) {
j = computed;
computed++;
}
process += 500;
if(process >= total) {
clearInterval(interval);
alert("done");
}
}, 10); // increase the delay
}, 1500);
}
DEMO