const sleep = (seconds = 0) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, seconds * 1000);
})
};
const CodingMan = (man = '') => {
const tasks = [];
tasks.push(() => {
console.log(`hello, ${man}`);
});
setTimeout(async () => {
for (const task of tasks) {
await task();
}
});
const obj = {
sleep: seconds => {
tasks.push(async () => {
await sleep(seconds);
console.log(`wake up after ${seconds}s`);
})
return obj;
},
eat: meal => {
tasks.push(() => {
console.log(`eat ${meal}~`);
});
return obj;
},
sleepHead: seconds => {
tasks.unshift(async () => {
await sleep(seconds);
console.log(`wake up after ${seconds}s`);
});
return obj;
}
}
return obj;
}
参考:https://juejin.cn/post/7425786548060848143?searchId=20241210224135F6FB528A861DE81279E9
实现CodingMan
于 2024-12-15 17:19:04 首次发布