4 回答

TA貢獻1801條經(jīng)驗 獲得超8個贊
發(fā)生的事情是,程序在 for 循環(huán)中競速,并幾乎立即設(shè)置了相對于 t=0s 的超時。如果你想使用 setTimeout(),你必須自己累積時間:
const data = [
{name: "Warm up", timeFormat: "00:10", time: 10},
{name: "High interval", timeFormat: "00:20", time: 20},
{name: "Low Interval", timeFormat: "00:05", time: 5},
{name: "High interval", timeFormat: "00:20", time: 20},
{name: "Low Interval", timeFormat: "00:05", time: 5},
]
function renderTimer(data) {
var timing = 0;
for (let i = 0; i < data.length; i++) {
const eachName = data[i].name;
timing += data[i].time;
setTimeout(() => {
console.log(eachName);
}, timing * 1000);
}
}
renderTimer(data);

TA貢獻1839條經(jīng)驗 獲得超15個贊
它的工作原理是await new Promise(...)
在 Promise 實現(xiàn)之前停止當前函數(shù)
const data = [
{name: "Warm up", timeFormat: "00:10", time: 10},
{name: "High interval", timeFormat: "00:20", time: 20},
{name: "Low Interval", timeFormat: "00:05", time: 5},
{name: "High interval", timeFormat: "00:20", time: 20},
{name: "Low Interval", timeFormat: "00:05", time: 5},
]
async function renderTimer(data) {
for (let i = 0; i < data.length; i++) {
const eachName = data[i].name;
const eachTime = data[i].time;
await new Promise(res => {
setTimeout(() => {
console.log(eachName);
// resolve the promise once the log is done
res()
}, eachTime * 100)}
)
// can't arrive here until the setTimeout is finalized
}
}
renderTimer(data);

TA貢獻2012條經(jīng)驗 獲得超12個贊
您也可以像這樣在遞歸函數(shù)中執(zhí)行此操作:
const data = [
{name: "Warm up", timeFormat: "00:10", time: 10},
{name: "High interval", timeFormat: "00:20", time: 20},
{name: "Low Interval", timeFormat: "00:05", time: 5},
{name: "High interval", timeFormat: "00:20", time: 20},
{name: "Low Interval", timeFormat: "00:05", time: 5},
]
const renderTimer = (data, i = 0) => {
setTimeout(() => {
console.log(data[i].name);
// Call for next data
if(i < data.length - 1)
renderTimer(data, i + 1);
}, data[i].time * 1000);
}
renderTimer(data);

TA貢獻1779條經(jīng)驗 獲得超6個贊
你可以這樣做:
const data = [
{name: "Warm up", timeFormat: "00:10", time: 10},
{name: "High interval", timeFormat: "00:20", time: 20},
{name: "Low Interval", timeFormat: "00:05", time: 5},
{name: "High interval", timeFormat: "00:20", time: 20},
{name: "Low Interval", timeFormat: "00:05", time: 5},
]
var time = 0;
function renderTimer(data) {
for (let i = 0; i < data.length; i++) {
const eachName = data[i].name;
time += data[i].time;
const eachTime = time * 1000;
setTimeout(() => {
console.log(eachName);
}, eachTime);
}
}
renderTimer(data);
添加回答
舉報