我想延迟for循环过程,以便加载数据看起来像进度条。 在此代码中,当我单击按钮时,它将直接显示此数据:20/20 Records Rendered。 我希望看到记录从1/20记录开始,然后在3秒后它将成为2/20记录渲染等等。
以下是代码:
<button name="subject" type="submit" value="6" onClick="Run(this.value)">Run</button>
<script>
function Run(value) {
custRecordsRendered = 0;
$.ajax({
type: 'Post',
url: "/Tasks/RunSample",
success: function (data) {
totalRecords = data[0].Total;
console.log("Total: " + data[0].Total);
console.log("Records: " + Object.keys(data).length);
for (var key in data) {
(function iterator() {
console.log("logs: "+data[key].Records);
setTimeout(iterator, 3000);
})();
if (data.hasOwnProperty(key)) {
custRecordsRendered = data[key].Records;
updateProgress();
}
}
}
});
function updateProgress() {
$("#completeCount").text(custRecordsRendered + "/" + totalRecords + " Records Rendered");
}
}
</script>
控制器:
public JsonResult RunSample()
{
List<object> countData = new List<object>();
int count = 20;
for (int i = 1; i <= count; i++)
{
countData.Add(new { Total = count, Records = i });
}
return Json(countData);
}
感谢您帮助我。
答案 0 :(得分:1)
如果我明白你的意思那么......这段代码可能就行了
function Run(value) {
custRecordsRendered = 0;
$.ajax({
type: 'Post',
url: "/Home/RunSample",
success: function (data) {
totalRecords = data[0].Total;
console.log("Total: " + data[0].Total);
console.log("Records: " + Object.keys(data).length);
var itemCount = 0;
var progressInterval = setInterval(function () {
if (itemCount < data.length) {
console.log(itemCount);
console.log("logs: " + data[itemCount].Records);
custRecordsRendered = data[itemCount].Records;
updateProgress();
itemCount++;
}
else {
clearInterval(progressInterval);
}
}, 500);
}
});
function updateProgress() {
$("#completeCount").text(custRecordsRendered + "/" + totalRecords + " Records Rendered");
}
}
在您的代码中,您正在处理setTimeout函数,就像它导致Thread休眠一样,但实际上,它并不是它设置的延迟异步事件将在指定的时间间隔后触发并执行处理函数,但是setTimeout调用之后的代码执行将继续..所以setInterval将为你服务