setTimeout是用來延遲執行代碼的函數,如果不小心使用不當可能會導致回調地獄。為了避免回調地獄,可以使用以下方法:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
delay(1000).then(() => {
// do something after 1 second
});
async function delayedAction() {
await delay(1000);
// do something after 1 second
}
delayedAction();
function delayAction(ms, callback) {
setTimeout(() => {
// do something
if (condition) {
delayAction(ms, callback);
}
}, ms);
}
delayAction(1000, () => {
// do something every 1 second
});
通過以上方法,可以有效地避免回調地獄,使代碼更加清晰和易于維護。