簡體   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