在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
在另一方面,如果你希望所有步驟同時被解僱(即獨立的阿賈克斯請求),這是你可以做的。
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實例,第二個是正在進行的增加。觀察控制檯以跟蹤執行情況。
[** Demo **](https://jsfiddle.net/tusharj/qwookbpx/1/) – Tushar
@Tushar:謝謝,但我想更新某些操作後的進度,如循環或整個函數,而不是在一段時間之後。 – user1170330