我正在运行一个长循环,需要报告循环的进度。
<script type="text/javascript">
var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(getListItemsCount, "sp.js");
function getListItemsCount() {
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
var list = web.get_lists().getByTitle("Child");
var camlQuery = new SP.CamlQuery();
this.listItems = list.getItems(camlQuery);
clientContext.load(listItems, 'Include(Id)');
clientContext.executeQueryAsync(function () {
alert(listItems.get_count());
},
function () {
alert('error');
});
}
</script>
我按照建议使用了window.setTimeout但仍然只在循环结束后才进行HTML页面更新...
答案 0 :(得分:1)
循环是同步的,因此它将一直运行直到它在setTimeout()
中的任何函数执行之前结束。
您必须将循环转换为函数,以便使用setTimeout
调用自身:
var mLog = document.getElementById("log");
var w, df, delta1, alfa; // fake implementation, for demo only
function chi_power(n) { return n; } // fake implementation, for demo only
var calc_power = 0, power = 5000; // fake data, for demo only
function calculate(n) {
if (n<10000 && calc_power<power) {
calc_power=chi_power(n,w,df,delta1,alfa);
var message="n="+n+"<br>";
progress(mLog,message);
// proceed with the loop
setTimeout(function () { calculate(n*2); }, 0);
}
}
function progress(mLog, message) {
mLog.innerHTML += message;
}
calculate(2);
&#13;
<div id="log"></div>
&#13;
答案 1 :(得分:0)
你的循环是同步的,但是setTimeout函数只会在循环结束后触发,因为调用循环的块仍然在堆栈上。如果要报告异步*的多个事物的进度,但是不要将它用于同步的事情,setTimeout可以工作。
您必须定期检查是否符合条件以显示进度,例如,在for循环中:
if (n % 500 === 0) progress(mLog, message);
答案 2 :(得分:0)
请通过递归检查异步方式:
var mLog=document.getElementById("log");
var n = 2;
function progress (mLog,message)
{
mLog.innerHTML+=message;
}
function asyncLoop(n) {
if(n >=10000) return;
//calc_power=chi_power(n,w,df,delta1,alfa);
var message="n="+n+"<br>";
progress(mLog,message);
window.setTimeout(asyncLoop(n*2), 0);
}
asyncLoop(n);
<div id = "log"> </div>