如何更新进度条?

时间:2016-04-24 15:07:17

标签: javascript jquery jquery-ui 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);

Here is a fiddle

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

在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();

Demo

在这种情况下,每个步骤都在前一个步骤中调用,以确保它们将按顺序从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();

Demo

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

相关问题