繁体   English   中英

如何更新进度条?

[英]How to update progress bar?

我正在尝试更新jQuery UI Progressbar的值。

初始化后,我运行一些循环。 在每个之后,我希望进度条更新其值。 但它只显示在最后的最终值,所以我没有看到每一步:

$("#progressbar").progressbar();

for (i = 0; i < 10000000; i++) {
  // takes some time...
}
$("#progressbar").progressbar("value", 25);

for (i = 0; i < 10000000; i++) {
  // takes some time...
}
$("#progressbar").progressbar("value", 50);

for (i = 0; i < 10000000; i++) {
  // takes some time...
}
$("#progressbar").progressbar("value", 75);

for (i = 0; i < 1000000000; i++) {
  // takes some time...
}
$("#progressbar").progressbar("value", 100);

这是一个小提琴

尝试在每个函数的末尾添加进度条值。

在Javascript中为测试目的模拟时间间隔的唯一可靠方法是使用setInterval和setTimeout。 循环运行得太快。

如果要确保按顺序执行步骤,可以执行此操作。 只需将setTimeout调用替换为您实际想要执行的操作即可。

function updateProgressbar($bar, value) {
    $bar.progressbar("value", value);
}

function step1() {
    setTimeout(function() {
    console.log('this is step 1');
    updateProgressbar($("#progressbar"), 25);
    step2();
  }, Math.random() * 2000 + 250);
}

function step2() {
    setTimeout(function() {
    console.log('this is step 2');
    updateProgressbar($("#progressbar"), 50);
    step3();
  }, Math.random() * 2000 + 250);
}

function step3() {
    setTimeout(function() {
    console.log('this is step 3');
    updateProgressbar($("#progressbar"), 75);
    step4();
  }, Math.random() * 2000 + 250);
}

function step4() {
    setTimeout(function() {
    console.log('this is step 4');
    updateProgressbar($("#progressbar"), 100);
  }, Math.random() * 2000 + 250);
}

$("#progressbar").progressbar();

console.log($("#progressbar").data('value'));

step1();

演示

在这种情况下,每个步骤都在前一个步骤内调用,以确保它们将按顺序从1到4进行调用。

另一方面,如果您希望同时触发所有步骤(即独立的ajax请求),这就是您可以做的。

function updateProgressbar($bar, step) {
    progress += step;
    $bar.progressbar("value", progress);
}

function step1() {
    setTimeout(function() {
    console.log('this is step 1');
    updateProgressbar($("#progressbar"), 25);
  }, Math.random() * 3000 + 1000);
}

function step2() {
    setTimeout(function() {
    console.log('this is step 2');
    updateProgressbar($("#progressbar"), 25);
  }, Math.random() * 3000 + 1000);
}

function step3() {
    setTimeout(function() {
    console.log('this is step 3');
    updateProgressbar($("#progressbar"), 25);
  }, Math.random() * 3000 + 1000);
}

function step4() {
    setTimeout(function() {
    console.log('this is step 4');
    updateProgressbar($("#progressbar"), 25);
  }, Math.random() * 3000 + 1000);
}

$("#progressbar").progressbar();

var progress = 0;

step1();
step2();
step3();
step4();

演示

在此示例中,所有四个步骤同时触发,但随机执行。 updateProgressbar函数接收2个参数,第一个是进度条的jQuery实例,第二个是进度增加 观察控制台以跟踪执行情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM