gpt4 book ai didi

使用回调的 JavaScript 异步填充条

转载 作者:行者123 更新时间:2023-12-03 08:15:45 25 4
gpt4 key购买 nike

我是 javascript 新手,不幸的是(或者幸运的是?)已经解决了 js 中异步事件的问题。我知道我们应该使用回调,并且我确实尝试过使用它们,但没有取得好的结果。

有 3 个函数,每个函数填充一个条形,我如何使用回调使条形依次填充?

var x1 = 0;
var x2 = 0;
var x3 = 0;
var lifeRemaining = 100 - (getPercentage(age, lifeExpectancy) + getPercentage(
effLifeRemaining, lifeExpectancy));

function ShowBar1() {
if (x1 < getPercentage(age, lifeExpectancy)) {
x1 += 1;
var y1 = "width: " + x1.toString() + "%";
progressBar1.setAttribute("style", y1);
progressBar1.textContent = x1.toString() + "%";
}
}

function ShowBar2() {
if (x2 < getPercentage(effLifeRemaining, lifeExpectancy)) {
x2 += 1;
var y2 = "width: " + x2.toString() + "%";
progressBar2.setAttribute("style", y2);
progressBar2.textContent = x2.toString() + "%"
}
}

function ShowBar3() {
if (x3 < lifeRemaining) {
x3 += 1;
var y3 = "width: " + x3.toString() + "%";
progressBar3.setAttribute("style", y3);
progressBar3.textContent = x3.toString() + "%";
}
}
setInterval(ShowBar1, 50);
setInterval(ShowBar2, 50);
setInterval(ShowBar3, 50);

最佳答案

如果有回调,则不需要使用间隔。您可以引用下面的回调示例:

var x1 = 0;
var x2 = 0;
var x3 = 0;
var lifeRemaining = 100 - (getPercentage(age, lifeExpectancy) + getPercentage(
effLifeRemaining, lifeExpectancy));

function ShowBar1(callback) {
if (x1 < getPercentage(age, lifeExpectancy)) {
x1 += 1;
var y1 = "width: " + x1.toString() + "%";
progressBar1.setAttribute("style", y1);
progressBar1.textContent = x1.toString() + "%";
}

return callback;
}

function ShowBar2(callback) {
if (x2 < getPercentage(effLifeRemaining, lifeExpectancy)) {
x2 += 1;
var y2 = "width: " + x2.toString() + "%";
progressBar2.setAttribute("style", y2);
progressBar2.textContent = x2.toString() + "%"
}

return callback;
}

function ShowBar3() {
if (x3 < lifeRemaining) {
x3 += 1;
var y3 = "width: " + x3.toString() + "%";
progressBar3.setAttribute("style", y3);
progressBar3.textContent = x3.toString() + "%";
}
}

var bar2 = ShowBar1(ShowBar2);
var bar3 = bar2(ShowBar3);
bar3();

您可以引用下面的回调,它会延迟 50 毫秒执行 3 函数。我只是删除了额外的代码以进行简化。

function ShowBar1(callback, callback2) {
console.log('ShowBar1');
callback(callback2);
}

function ShowBar2(callback) {
console.log('ShowBar2');
callback();
}

function ShowBar3() {
console.log('ShowBar3');

setTimeout(ShowBar1, 50, ShowBar2, ShowBar3);
}

ShowBar1(ShowBar2, ShowBar3);

关于使用回调的 JavaScript 异步填充条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33948407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com