-
Notifications
You must be signed in to change notification settings - Fork 509
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
【Q754】实现 LazyMan #810
Labels
Comments
function LazyMan(name) {
console.log(`Hi! This is ${name}!`);
}
LazyMan.prototype.sleep = function(time) {
const timeInMiliSec = time * 1000;
const start = performance.now();
console.log(`Wait for ${time} seconds...`);
while (performance.now() - start <= timeInMiliSec) {}
console.log(`Wake up after ${time} seconds.`);
return this;
}
LazyMan.prototype.sleepFirst = function(time) {
return this.sleep(time);
}
LazyMan.prototype.eat = function(thing) {
console.log(`Eat ${thing}~~`);
return this;
} |
function 方式 function LazyMan(name) {
if (!(this instanceof LazyMan)) {
return new LazyMan(name);
}
this.tasks = [];
// 添加初始问候任务
this.tasks.push(async () => {
console.log(`Hi! This is ${name}!`);
});
// 开始执行任务队列
this.runTasks();
return this;
}
LazyMan.prototype.runTasks = async function() {
setTimeout(async () => {
for (const task of this.tasks) {
await task();
}
}, 0);
};
LazyMan.prototype.sleep = function(seconds) {
this.tasks.push(async () => {
console.log(`等待${seconds}秒..`);
await new Promise(resolve => setTimeout(resolve, seconds * 1000));
console.log(`Wake up after ${seconds}`);
});
return this;
};
LazyMan.prototype.sleepFirst = function(seconds) {
this.tasks.unshift(async () => {
console.log(`等待${seconds}秒..`);
await new Promise(resolve => setTimeout(resolve, seconds * 1000));
console.log(`Wake up after ${seconds}`);
});
return this;
};
LazyMan.prototype.eat = function(food) {
this.tasks.push(async () => {
console.log(`Eat ${food}~`);
});
return this;
}; 以及 class 方式 class LazyLazyMan {
constructor(name) {
this.tasks = [];
// 添加初始问候任务
this.tasks.push(async () => {
console.log(`Hi! This is ${name}!`);
});
// 开始执行任务队列
this.runTasks();
}
async runTasks() {
setTimeout(async () => {
for (const task of this.tasks) {
await task();
}
}, 0);
}
sleep(seconds) {
this.tasks.push(async () => {
console.log(`等待${seconds}秒..`);
await new Promise(resolve => setTimeout(resolve, seconds * 1000));
console.log(`Wake up after ${seconds}`);
});
return this;
}
sleepFirst(seconds) {
this.tasks.unshift(async () => {
console.log(`等待${seconds}秒..`);
await new Promise(resolve => setTimeout(resolve, seconds * 1000));
console.log(`Wake up after ${seconds}`);
});
return this;
}
eat(food) {
this.tasks.push(async () => {
console.log(`Eat ${food}~`);
});
return this;
}
}
function LazyMan(name) {
return new LazyLazyMan(name);
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: