在 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 实例,第二个是正在进行的 increase。观察控制台以跟踪执行情况。