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
});
通过以上方法,可以有效地避免回调地狱,使代码更加清晰和易于维护。